🧠 Python Concept That Powers @property & Methods: __set_name__ Hidden hook during class creation 👀 🤔 What Is __set_name__? When a class is created, Python tells each descriptor: 👉 “Hey, your attribute name is x.” That hook is __set_name__. 🧪 Example 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 class User: age = Field() name = Field() u = User() u.age = 20 print(u.age) The descriptor automatically knows its field name 🎯 🧒 Simple Explanation Imagine giving kids name badges 🏷️ The teacher tells each kid: 👉 “Your name is Asha.” That’s __set_name__. 💡 Why This Is Powerful ✔ Self-aware descriptors ✔ ORM-like fields ✔ Framework internals ✔ Cleaner reusable components ⚡ Real-World Use 💻 Django models 💻 ORMs 💻 Validation frameworks 💻 Data descriptors 🐍 Python classes don’t just define attributes. 🐍 They introduce them by name 🐍 __set_name__ is one of those hooks you never see — but frameworks rely on it. #Python #PythonTips #PythonTricks #AdvancedPython #CleanCode #LearnPython #Programming #DeveloperLife #DailyCoding #100DaysOfCode
Sahina Rayeesa’s Post
More Relevant Posts
-
🧠 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
-
-
🧠 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
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
-
-
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
-
-
🧠 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
-
-
👉I wish someone told me these Python tricks earlier… ✍ When I first started coding in Python, my code worked…but it wasn’t clean, readable, or efficient. 💻 Over time, I discovered a few simple tricks that instantly made my code look more professional and Pythonic. Here are 5 Python tricks that can make your code 10x cleaner 👇 🐍 1. List Comprehensions instead of long loops Instead of writing multiple lines: squares = [] for i in range(10): squares.append(i*i) Write it in one clean line: squares = [i*i for i in range(10)] ⚡ 2. Use enumerate() instead of manual counters Instead of: i = 0 for item in items: Use: for i, item in enumerate(items): Cleaner and less error-prone. 🔁 3. Swap variables in one line No temporary variable needed: a, b = b, a This is one of the coolest Python features. 🔗 4. Loop through multiple lists using zip() for name, score in zip(names, scores): Much cleaner than using indexes. ✨ 5. Use f-strings for readable output name = "Alice" print(f"Hello {name}") Way better than string concatenation or .format(). 💡 Small tricks like these make a big difference in writing clean and maintainable code. What’s your favorite Python trick that developers should know? Let’s share and learn from each other in the comments 👇 #Python #CodingTips #SoftwareDevelopment #CleanCode #Developers #FullStackDeveloper
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
-
-
Python Fundamentals That Separate Beginners from Pros 😎 -- Understanding Python data types is one of the first real steps toward becoming confident in Python. Here’s a simple breakdown 👇 🔹 String (str) Immutable Ordered & indexable Can have duplicate characters Stores text (sequence of characters) 🔹 List (list) Mutable Ordered & indexable Allows duplicates Can store any type of data (int, str, list, dict, etc.) 🔹 Tuple (tuple) Immutable Ordered & indexable Allows duplicates Can store any type of data Single element tuple must have a comma → ("Techie",) 🔹 Set (set) Mutable Unordered & not indexable Does NOT allow duplicates Stores only hashable (immutable) values like int, str, tuple Empty set is set() (not {}) 🔹 Dictionary (dict) Mutable Insertion ordered (Python 3.7+) Keys must be unique and hashable Values can be duplicated Accessed by keys, not index Empty dictionary is {} Strong fundamentals make advanced topics easier. Master the basics, and everything else becomes clearer. 🚀 #Python #Programming #DataScience #Learning #Dataanalyst
To view or add a comment, sign in
-
-
Accessing Dictionary Values Safely in Python Dictionaries are powerful data structures in Python that store data as key-value pairs, allowing for efficient access. Accessing items correctly is essential, especially when the existence of a key is uncertain. The most straightforward way to retrieve a value is by using the key directly, as shown with `person['name']`. This method works seamlessly, but if a key does not exist, Python raises a `KeyError`, potentially leading to runtime errors. That's where the `get` method becomes advantageous. It allows for safe retrieval; if the key isn’t found, it returns `None` instead of causing a crash. Another valuable feature of the `get` method is its ability to specify a default return value. In our example, when looking for 'country', if it doesn’t exist, we can have it return 'Unknown'. This ability is particularly useful in real-world applications, ensuring that our code remains robust and gracefully handles missing data. Understanding the difference between direct access and the `get` method becomes crucial when working with dynamic datasets or user-generated content, where missing keys are commonplace. The choice of method can significantly impact how well your code handles such situations. Quick challenge: In what scenario would you prefer to use the `get` method over direct key access when dealing with dictionaries? #WhatImReadingToday #Python #PythonProgramming #Dictionaries #PythonTips #Programming
To view or add a comment, sign in
-
-
Python Tip Every Beginner Should Know One concept that saves you from many bugs in Python Mutable vs Immutable Objects In Python, some objects can change after creation, while others cannot. 🔹 Immutable Objects (cannot change) Examples: int, float, string, tuple x = 10 x = x + 5 print(x) Here Python creates a new object instead of modifying the original one. Another example: name = "Python" name[0] = "J" # Error Strings are immutable, so their values cannot be changed. 🔹 Mutable Objects (can change) Examples: list, dictionary, set numbers = [1, 2, 3] numbers.append(4) print(numbers) Output: [1, 2, 3, 4] Here the same list object is modified. 💡 Why this matters? If you pass a list to a function, the original data can change. def add_item(lst): lst.append(100) data = [1, 2, 3] add_item(data) print(data) Output: [1, 2, 3, 100] Understanding this concept helps a lot in: ✔ Data Analysis ✔ Machine Learning ✔ Writing clean Python code 📌 Tip: If you want to avoid modifying the original list: new_list = old_list.copy() Small Python concepts like this make a big difference in writing better code. If you're learning Python, remember this: Mutable → Can change Immutable → Cannot change If you're learning Python, mastering small concepts like this makes a big difference. #Python #PythonProgramming #Coding #DataScience #LearnPython #ProgrammingTips #DataAnalyst
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