🧠 Python Concept That Controls Attribute Access: __getattribute__ vs __getattr__ They sound similar… but behave very differently 👀 🤔 The Difference 💻 __getattribute__ → runs for every attribute access 💻 __getattr__ → runs only if attribute not found 🧪 Example class Demo: def __getattribute__(self, name): print("getattribute:", name) return super().__getattribute__(name) def __getattr__(self, name): print("getattr:", name) return "default" d = Demo() d.x = 10 print(d.x) print(d.y) ✅ Output getattribute: x 10 getattribute: y getattr: y default 🧒 Simple Explanation Imagine asking your mom for things 👩 💻 __getattribute__ → mom checks every request 💻 __getattr__ → mom answers only if not found 💡 Why This Is Powerful ✔ Lazy attributes ✔ Proxies & wrappers ✔ Debugging tools ✔ Framework internals ⚠️ Important Rule Inside __getattribute__ always call: super().__getattribute__(name) Otherwise → infinite recursion 😬 🐍 Python lets you intercept attribute access itself 🐍 Understanding __getattribute__ vs __getattr__ unlocks advanced OOP patterns. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
Python attribute access control: __getattribute__ vs __getattr__
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
-
-
🧠 Python Concept That Changes Instance Checks: __instancecheck__ & __subclasscheck__ You can redefine what isinstance() means 👀 🤔 The Surprise Normally: isinstance(obj, MyClass) Python checks inheritance. But classes can override this logic. 🧪 Example class Even: def __instancecheck__(self, instance): return isinstance(instance, int) and instance % 2 == 0 even = Even() print(isinstance(4, even)) # True print(isinstance(5, even)) # False Now “Even” behaves like a virtual type 🎯 🧒 Simple Explanation 🎟️ Imagine a club 🎟️ Guard doesn’t check family. 🎟️ He checks: “Are you even?” 🎟️ That rule = __instancecheck__. 💡 Why This Is Powerful ✔ Virtual types ✔ Flexible APIs ✔ Type systems ✔ Plugin interfaces ✔ Advanced frameworks ⚡ Related Hook __subclasscheck__(cls, subclass) Controls issubclass(). 🐍 In Python, type checks aren’t fixed 🐍 Classes can redefine what “instance of” means. 🐍 __instancecheck__ turns types into behavior rules. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
🚀 "if __name__ == "__main__"" When I first started writing Python scripts, I often saw this line and ignored it: Later I realized — this small line controls how your code behaves when executed vs imported. 🔹 Every Python file has a special variable called "__name__". - When the file is run directly, Python sets: __name__ = "__main__" - When the file is imported into another file, Python sets: __name__ = "module_name" So this condition: if __name__ == "__main__": means: 👉 “Run the code inside this block only when the file is executed directly, not when it is imported.” --- 💡 Why is this powerful? - Keeps testing/demo code separate from reusable functions - Prevents unwanted execution when modules are imported - Helps create clean, production-ready Python modules --- 📌 Example: def add(a, b): return a + b if __name__ == "__main__": print(add(2, 3)) # runs only when executed directly When imported, only the function is available — the test code doesn’t run. --- Small Python habits like this make your code cleaner, reusable, and professional. #Python #Programming #CodingTips #SoftwareDevelopment #LearnPython
To view or add a comment, sign in
-
-
🧠 Python Concept That Explains Attribute Lookup Order: Descriptor Lookup Chain When you access: obj.attr Python follows a precise order 👀 🔍 The Real Lookup Order Python checks in this exact sequence: 1️⃣ Data descriptor (__set__ / __delete__) 2️⃣ Instance __dict__ 3️⃣ Non-data descriptor (__get__) 4️⃣ Class __dict__ 5️⃣ __getattr__ 🧪 Example Insight class D: def __get__(self, obj, owner): return "descriptor" class C: x = D() c = C() c.x = "instance" print(c.x) ✅ Output instance Because instance dict beats non-data descriptor. 🧒 Explain Like I’m 5 Imagine looking for a toy 🧸 1️⃣ Guard holding it 2️⃣ Your bag 3️⃣ Shelf 4️⃣ Store 5️⃣ Ask someone That order = lookup chain. 💡 Why This Matters ✔ Descriptor behavior ✔ Properties ✔ ORMs ✔ Framework internals ✔ Debugging weird attribute bugs ⚡ Key Rule 🐍 Data descriptors override instance attributes. 🐍 Non-data descriptors don’t. 🐍 Attribute access in Python isn’t random. 🐍 It follows a precise chain 🐍 Understanding the descriptor lookup order explains many “magic” behaviors. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
🧠 Python Concept That Explains Class Namespaces: __prepare__ in Metaclasses Before a class is created… Python prepares its namespace 👀 🤔 What Is __prepare__? When Python executes: class MyClass: x = 1 y = 2 It first asks the metaclass: 👉 “What mapping should I use to store attributes?” That hook = __prepare__. 🧪 Example class OrderedMeta(type): @classmethod def __prepare__(mcls, name, bases): return {} def __new__(mcls, name, bases, namespace): print(list(namespace.keys())) return super().__new__(mcls, name, bases, namespace) class Demo(metaclass=OrderedMeta): a = 1 b = 2 c = 3 ✅ Output ['a', 'b', 'c'] Metaclass saw class body order 🎯 🧒 Simple Explanation 🧸 Before kids put toys in a box, teacher chooses the box. 🧸 That box = namespace. 🧸 Choice = __prepare__. 💡 Why This Matters ✔ Ordered class attributes ✔ DSLs & frameworks ✔ Enum internals ✔ ORM field order ✔ Metaprogramming ⚡ Real Uses 💻 Enum preserves order 💻 Dataclasses fields 💻 ORM column order 💻 Serialization frameworks 🐍 In Python, even class bodies have a setup phase 🐍 __prepare__ decides how attributes are collected, before the class even exists. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
🔥 Python Set Methods If you're learning Python, mastering sets is a must! Here's a simple and clean reference 👇 📌 Python Set Methods Table Input → Method → Output {1, 2} → .add(3) → {1, 2, 3} {1, 2, 3} → .remove(2) → {1, 3} {1, 2, 3} → .discard(4) → {1, 2, 3} {1, 2, 3} → .pop() → Random element removed {1, 2} → .update({3, 4}) → {1, 2, 3, 4} {1, 2, 3} → .clear() → set() {1, 2} → .union({3, 4}) → {1, 2, 3, 4} {1, 2, 3} → .intersection({2, 3, 4}) → {2, 3} {1, 2, 3} → .difference({2}) → {1, 3} {1, 2} → .symmetric_difference({2, 3}) → {1, 3} {1, 2} → .issubset({1, 2, 3}) → True {1, 2, 3} → .issuperset({1, 2}) → True {1, 2} → .isdisjoint({3, 4}) → True {1, 2} → .copy() → {1, 2} 💡 Pro Tip: Use .discard() instead of .remove() when you're not sure if the element exists. 📚 Save this for quick revision & share with your friends! #Python #Coding #Programming #Developers #LearnPython #CodingTips #DataStructures
To view or add a comment, sign in
-
-
𝗦𝘁𝗼𝗽 𝗪𝗿𝗶𝘁𝗶𝗻𝗴 𝗣𝘆𝘁𝗵𝗼𝗻 𝗟𝗶𝗸𝗲 𝗮 𝗕𝗲𝗴𝗶𝗻𝗻𝗲𝗿 — 𝗗𝗼 𝗧𝗵𝗶𝘀 𝗜𝗻𝘀𝘁𝗲𝗮𝗱 I see this in code frequently. 𝗗𝗲𝘃𝗲𝗹𝗼𝗽𝗲𝗿𝘀 𝘄𝗵𝗼 𝗸𝗻𝗼𝘄 𝗣𝘆𝘁𝗵𝗼𝗻 𝗯𝘂𝘁 𝗮𝗿𝗲𝗻'𝘁 𝘄𝗿𝗶𝘁𝗶𝗻𝗴 𝗣𝘆𝘁𝗵𝗼𝗻𝗶𝗰 𝗰𝗼𝗱𝗲. There's a difference between code that works and code that belongs in Python. Look at the two examples in the image. 𝗦𝗮𝗺𝗲 𝗼𝘂𝘁𝗽𝘂𝘁. 𝗕𝘂𝘁 𝗼𝗻𝗲 𝗿𝗲𝗮𝗱𝘀 𝗹𝗶𝗸𝗲 𝗮 𝘁𝗿𝗮𝗻𝘀𝗹𝗮𝘁𝗲𝗱 𝗖 𝗽𝗿𝗼𝗴𝗿𝗮𝗺. The other reads like Python. Here are the patterns I see developers overuse and what to do instead: ❌ Manual index loops → ✅ enumerate() ❌ Building lists with .append() in loops → ✅ list comprehensions ❌ Checking "if len(x) > 0" → ✅ just "if x" ❌ Manual min/max logic → ✅ built-in min(), max() with key= ❌ Catching bare Exception → ✅ catch specific exceptions 𝗡𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲𝘀𝗲 𝗮𝗿𝗲 𝗮𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗣𝘆𝘁𝗵𝗼𝗻. They're just Python being Python. When I started, I wrote Python like I was still thinking in C. It took real project work like building actual APIs and handling real data before these patterns became instinct. The shift happens when you stop learning syntax and start reading great Python code written by others. 𝗪𝗵𝗶𝗰𝗵 𝗼𝗳 𝘁𝗵𝗲𝘀𝗲 '𝗯𝗲𝗴𝗶𝗻𝗻𝗲𝗿 𝘁𝗿𝗮𝗽𝘀' 𝗱𝗶𝗱 𝘆𝗼𝘂 𝗳𝗮𝗹𝗹 𝗶𝗻𝘁𝗼 𝘁𝗵𝗲 𝗹𝗼𝗻𝗴𝗲𝘀𝘁 𝗯𝗲𝗳𝗼𝗿𝗲 𝗳𝗶𝗻𝗮𝗹𝗹𝘆 𝗯𝗿𝗲𝗮𝗸𝗶𝗻𝗴 𝘁𝗵𝗲 𝗵𝗮𝗯𝗶𝘁? #Python #PythonTips #CleanCode #BackendDevelopment #LearnPython #SoftwareEngineering
To view or add a comment, sign in
-
-
🧠 Python Concept That Hooks Attribute Definition: __set_name__ vs Descriptors Naming Wait… how does a descriptor know its attribute name? 👀 class User: age = Field() How does Field know it’s called "age"? 🤯 🧪 The Hook: __set_name__ class Field: def __set_name__(self, owner, name): self.name = name def __get__(self, instance, owner): return instance.__dict__.get(self.name) def __set__(self, instance, value): instance.__dict__[self.name] = value Now descriptors auto-know their field name 🎯 🧒 Simple Explanation Teacher gives each student a badge 🏷️ “Your name is Asha.” Descriptor gets its badge when class is created. 💡 Why This Is Powerful ✔ ORM fields ✔ Validation systems ✔ Framework internals ✔ Reusable descriptors ✔ Clean DSL design ⚡ Real Uses 💻 Django model fields 💻 Dataclasses internals 💻 Pydantic fields 💻 Serialization libraries 🐍 In Python, attributes introduce themselves 🐍 __set_name__ lets descriptors learn their own name, the moment the class is created. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
To view or add a comment, sign in
-
-
How & What Python Class objects Did you know every class in Python is actually an object created by the type metaclass? - When we write a simple class like: class MyClass: pass - Python internally does something similar to this: MyClass = type("MyClass", (), {}) ◽ Yes, that means classes themselves are objects created dynamically at runtime. - Understanding the internals ◽ When you create an instance: obj = MyClass() ◽ Python internally calls: type.call(MyClass) ◽ Which further triggers the following sequence: 1. __new__(cls) → Starts object creation 2. object.__new__(cls) → Allocates memory 3. __init__(self) → Initializes the object ◽ So the real flow looks like: type.call(cls) ↓ cls.new(cls) ↓ object.new(cls) ↓ cls.init(obj) - But here's where things get interesting... By overriding the __call__ method inside a custom metaclass, we can manipulate how objects are created. - Example idea: class CustomizedMetaClass(type): def call(cls, *args, **kwargs): print("Object creation intercepted") return "Manipulated Reference" Now every time the class is called, instead of returning a normal object, it can return anything we want. ◽ This means we can control: • Object creation • Class behavior • Validation logic • Singleton patterns • Framework-level abstractions ◽ This is exactly why metaclasses are used in frameworks like Django, SQLAlchemy, and ORMs. - Key Takeaways ◽ In Python, everything is an object (including classes) ◽ Classes are created using the type metaclass ◽ type.__call__() controls object instantiation ◽ Metaclasses allow deep customization of class behavior Understanding this concept unlocks the real power of Python's object model. Github repo - https://lnkd.in/gkcGcunj #Python #PythonProgramming #PythonInternals #MetaProgramming #Metaclass #AdvancedPython #BackendDevelopment #Programming #CodeNewbie #DataScience
To view or add a comment, sign in
-
Your Python lists aren't just static storage boxes. They are active, dynamic assembly lines. 🏭 ⠀ Beginners often learn how to create a list, and then they just... leave it alone. ⠀ But real-world applications require data that changes. ⠀ Think of a shopping cart. You don't just put things in once. You add items, you realize you don't need that third bag of chips and remove it, or you take the last item out to scan it at checkout. ⠀ To move from beginner to intermediate Python, you need to master the four "magic verbs" of list mutation: ⠀ 1️⃣ `.append()`: The Quick Add. Toss an item onto the very end of the pile. Easy. ⠀ 2️⃣ `.insert()`: The Precision Strike. Need something exactly at spot #2? This method slides everything else over to make room. ⠀ 3️⃣ `.remove()`: The Search & Destroy. "Find the 'Rotten Apple' and get rid of it." You tell Python the exact *value* you want gone, not the index. But here is the catch beginners miss: if you have three 'Rotten Apples' in your list, `.remove()` only destroys the very first one it finds and then stops. ⠀ 4️⃣ `.pop()`: The Grab & Go. This is the coolest one. It doesn't just delete an item from the end; it *hands it to you*. It removes the item and returns it so you can use it immediately. ⠀ Stop treating your data like it's carved in stone. Start managing it like a pro. ⠀ We turn boring Python documentation into a friendly, 3-minute daily habit. ☕ ⠀ 👇 Join the Class of 2026 and get tomorrow's lesson delivered free: https://lnkd.in/ducXvs-y ⠀ #Python #DataStructures #CodingTips #SoftwareDevelopment #LearnToCode #PyDaily
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