🧠 Python Concept That Lets Objects Customize Access: __slots__ vs __dict__ 🧠 Every object normally stores attributes in a dictionary 🧠 But you can remove that dictionary entirely 🤔 Default Behavior class User: def __init__(self, name, age): self.name = name self.age = age u = User("Asha", 20) print(u.__dict__) Objects keep attributes in __dict__. ✅ Using __slots__ class User: __slots__ = ("name", "age") def __init__(self, name, age): self.name = name self.age = age Now: ⚡ No __dict__ ⚡ Less memory ⚡ Faster access 🧒 Simple Explanation 🎒 Normal object = backpack You can put anything inside. 🍱 __slots__ object = fixed tray Only specific places allowed. 💡 Why This Is Powerful ✔ Memory optimization ✔ Large datasets ✔ Game / simulation objects ✔ Performance-critical apps ⚠️ Important Limits u.city = "Delhi" # ❌ AttributeError 💻 Only declared slots allowed. 🐍 Python objects are flexible by default. 🐍 __slots__ makes them compact and strict 🐍 Sometimes structure beats flexibility. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
Python __slots__ vs __dict__ for Customizable Objects
More Relevant Posts
-
🧠 Python Concept That Runs When Class Is Called: __call__ on Classes Objects can be callable… but classes can customize calls too 👀 🤔 The Surprise When you do: obj = MyClass() Python actually does: obj = MyClass.__call__() 🧪 Example class Logger: def __call__(self, msg): print("LOG:", msg) log = Logger() log("Hello") 🎯 Class instances become functions 🧠 But Classes Themselves Use __call__ class Meta(type): def __call__(cls, *args, **kwargs): print("Creating instance") return super().__call__(*args, **kwargs) class User(metaclass=Meta): pass u = User() ✅ Output Creating instance Metaclass intercepted construction. 🧒 Simple Explanation 🥤 Imagine a vending machine 🥤 Press button → machine runs → gives item 🥤 That press = __call__. 💡 Why This Is Powerful ✔ Factories ✔ Dependency injection ✔ Framework hooks ✔ Callable objects ✔ Advanced APIs ⚡ Real Uses 💻 PyTorch modules 💻 FastAPI dependencies 💻 Decorator classes 💻 DSL builders 🐍 In Python, calling isn’t just for functions 🐍 Classes and objects can redefine what “()” means. 🐍 __call__ is the hook behind that power. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
You're making your Python code 10x slower. I did the same thing for months. Here's the mistake: I was using loops everywhere. For EVERYTHING. Want to multiply every number in a list by 2? for loop. Want to filter data? for loop. Want to calculate column averages? for loop. Then someone showed me vectorization. Same operation. 100x faster. Here's the difference: ❌ The slow way (what I used to do): result = [] for i in data: result.append(i * 2) ✅ The fast way (vectorization): result = data * 2 When you're working with 10 rows? Doesn't matter. When you're working with 10 million rows? Game changer. My delivery prediction model went from taking 45 minutes to run to 3 minutes. Same output. Just smarter code. Three beginner-friendly vectorization tips: 1. Use NumPy/Pandas operations instead of loops → df['new_col'] = df['old_col'] * 2 (not a loop) 2. Use .apply() for complex operations → df['result'] = df['column'].apply(lambda x: custom_function(x)) 3. Use built-in functions (.sum(), .mean(), .max()) → df['column'].sum() (not sum = 0; for i in df...) Your code doesn't need to be perfect. But it should be efficient. Especially when you're building production-ready models. What's one Python optimization trick you wish you'd learned earlier? Drop it below — let's help each other level up. 👇 #Python #DataScience #MachineLearning #CodingTips #Programming
To view or add a comment, sign in
-
🚀 The Python Speed Stack 1. Optimize the Logic (The "Low Hanging Fruit") Before switching engines, check your oil. Built-ins: Use map(), filter(), and list comprehensions. They run at C-speed under the hood. Vectorization: If you are doing math in a for loop, you’re doing it wrong. Use NumPy or Pandas to push calculations into optimized C arrays. 2. The CPython Shortcuts Slots: Use __slots__ in your classes to prevent the creation of __dict__, saving memory and speeding up attribute access. Memshells: Use lru_cache from functools to avoid re-calculating expensive functions. 3. Change the Runtime If CPython is the bottleneck, swap the engine: PyPy: A JIT (Just-In-Time) compiler that can make long-running programs 5x–10x faster without changing a single line of code. Cython: Explicitly declare C types in your Python code. It compiles your .py into a C extension, giving you C-level performance while keeping Python syntax. 4. Parallelism vs. Concurrency I/O Bound? Use asyncio. It handles thousands of connections without the overhead of threads. CPU Bound? Use multiprocessing to bypass the GIL (Global Interpreter Lock) and utilize every core on your machine. 💡 The Golden Rule: Profile First Don't guess where the bottleneck is. Use cProfile or line_profiler to find the exact line slowing you down. Optimization without profiling is just organized guessing. What’s your go-to trick for speeding up a sluggish Python script? Let’s talk in the comments! 👇 #Python #SoftwareEngineering #Cython #ProgrammingTips #BackendDevelopment #DataScience #PerformanceOptimization #CodingLife
To view or add a comment, sign in
-
🧠 Python Concept That Makes Objects Behave Like Dictionaries: __getitem__ You can make your own objects work with [] indexing 👀 🤔 The Surprise Normally: data = [10, 20, 30] print(data[1]) # 20 But you can enable the same behavior in your own class. 🧪 Example class Book: def __init__(self): self.pages = ["Intro", "Chapter 1", "Chapter 2"] def __getitem__(self, index): return self.pages[index] b = Book() print(b[0]) # Intro print(b[1]) # Chapter 1 Now your object behaves like a list 🎯 🧒 Simple Explanation 📖 Imagine a book 📖 When someone asks for page 2, the librarian opens the book and gives it. 📖 That librarian = __getitem__. 💡 Why This Is Powerful ✔ Custom containers ✔ Database record access ✔ Pandas / NumPy behavior ✔ Clean APIs ⚡ Fun Fact These operators map to methods: obj[x] → __getitem__ obj[x]=y → __setitem__ del obj[x] → __delitem__ 🐍 In Python, [ ] isn’t just for lists. 🐍 Any object can support indexing 🐍 __getitem__ is the hook behind it. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 Day 7/70 – Loops in Python (for & while) Today I learned about Loops in Python 🐍 Loops help us repeat tasks automatically. In data analytics, loops are used to process large datasets. 📌 1️⃣ For Loop Used to iterate over a sequence (like a list). numbers = [10, 20, 30, 40] for num in numbers: print(num) 👉 This prints each value one by one. 📌 2️⃣ Using range() for i in range(5): print(i) Output: 0 1 2 3 4 📌 3️⃣ While Loop Repeats until a condition becomes False. count = 1 while count <= 5: print(count) count += 1 📊 Data Analytics Example marks = [70, 80, 90, 60] total = 0 for mark in marks: total += mark average = total / len(marks) print("Average:", average) This is basic data calculation logic 🔥 💡 Why Loops Are Important? ✔ Processing large datasets ✔ Automating repetitive tasks ✔ Applying conditions to multiple records ✔ Foundation for Pandas operations #Day7 #Python #DataAnalytics #LearningInPublic #FutureDataAnalyst
To view or add a comment, sign in
-
-
🧠 Python Concept That Explains Why += Can Mutate: In-place vs New Objects (__iadd__) Why does this behave differently? 👀 a = [1, 2] b = a a += [3] print(a) # [1, 2, 3] print(b) # [1, 2, 3] But: x = (1, 2) y = x x += (3,) print(x) # (1, 2, 3) print(y) # (1, 2) Same += … different result 🤯 🤔 The Reason: __iadd__ Python tries: 1️⃣ __iadd__ (in-place add) 2️⃣ else → __add__ (new object) 🧪 Lists implement __iadd__ list.__iadd__(self, other) So list is modified in place. 🧪 Tuples don’t So Python creates a new tuple. 🧒 Simple Explanation List = clay 🧱 You reshape same clay. Tuple = brick 🧱 You must make new brick. 💡 Why This Matters ✔ Mutability understanding ✔ Side-effects bugs ✔ Performance ✔ Data structures ✔ Interview classic ⚡ Key Insight id(a) == id(a += ...) True for mutable types False for immutable types 💻 In Python, += doesn’t always mean “new value”. 🐍 Sometimes it means “modify in place” 🐍 The difference comes from __iadd__. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
Mastering strings in Python is one of those “small” skills that quietly powers almost everything we build—APIs, data pipelines, web apps, you name it. This week I revisited the fundamentals of Python strings: - Creating and slicing strings to access and update specific parts - Formatting with `format()` to build clean, readable outputs - Leveraging powerful built-in methods like `strip()`, `split()`, `join()`, `find()`, `replace()`, and case conversions (`lower()`, `upper()`, `title()`) to clean and transform text efficiently What struck me again is how much you can do *just* with string methods before reaching for heavier tools. If you’re starting with Python (or even revisiting basics), investing time in string operations is one of the highest-ROI steps you can take as a developer or data professional.
To view or add a comment, sign in
-
🚀 Day 5/60 – If-Else Conditions (Make Decisions in Python) Your code shouldn’t just run. It should think and decide. That’s where if-else comes in 👇 🧠 What is If-Else? It helps your program make decisions based on conditions. ✅ Basic Example age = 20 if age >= 18: print("You can vote") else: print("You cannot vote") 👉 If condition is True → first block runs 👉 Else → second block runs 🔁 Multiple Conditions (elif) marks = 75 if marks >= 90: print("Grade A") elif marks >= 60: print("Grade B") else: print("Fail") ⚡ Real-World Example temperature = 35 if temperature > 30: print("It's hot") elif temperature > 20: print("Nice weather") else: print("It's cold") ❌ Common Mistake if age > 18 print("Adult") # ❌ Missing colon Correct: if age > 18: print("Adult") # ✅ 🔥 Pro Tip Indentation matters in Python 👇 if True: print("Hello") # ❌ Error if True: print("Hello") # ✅ 🔥 Challenge for today Write a program: 👉 Take a number 👉 Check if it is: • Positive • Negative • Zero Comment “DONE” when you solve it ✅ Follow Adeel Sajjad to stay consistent for 60 days 🚀 #Python #LearnPython #PythonProgramming #Coding #Programming
To view or add a comment, sign in
-
-
Over the last few days I've been building a small data analysis toolkit in Python. The idea is simple: Instead of solving the same data cleaning problems again and again across different projects, I want to create a small reusable set of functions. So far I've implemented a function for cleaning and normalizing column names in Pandas DataFrames: lowercase, removing whitespace, replacing spaces with underscores, etc. Right now I'm working on the next part: handling duplicates. The goal is to build a function that can: - detect duplicates - report them - automatically clean them depending on the chosen action Besides writing the function itself, I'm also focusing on: - writing clear docstrings - input validation - and adding tests It's a small step, but building things from scratch is one of the best ways I've found to really understand how tools work under the hood. More updates soon as the toolkit grows. #python #pandas #dataanalysis #machinelearning #learninginpublic
To view or add a comment, sign in
-
-
🧠 Python Concept: is vs == ✨ Both compare values, but they check different things. ✨ == → Checks value equality a = [1, 2, 3] b = [1, 2, 3] print(a == b) Output True Because both lists have the same values. ✨ is → Checks object identity a = [1, 2, 3] b = [1, 2, 3] print(a is b) Output False Because they are different objects in memory. 🧪 Example with None value = None if value is None: print("Value is None") Using is is the recommended way to check None. 🧒 Simple Explanation 📚 Imagine two identical books 📚 == → checks if the content is the same 📚 is → checks if it is the exact same book 💡 Why This Matters ✔ Avoid logic bugs ✔ Important for None checks ✔ Helps understand Python memory ✔ Common interview question 🐍 In Python, == compares values, while is compares identities 🐍 Two objects may look the same but still be different in memory. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development