Understanding Descriptors in Python: Attributes, Methods, and Use Cases

🧠 What is a Descriptor in Python ? A descriptor is any object that defines one or more of these methods: __get__() → Access attribute __set__() → Set attribute __delete__() → Delete attribute 👉 In simple terms: Descriptors control how attributes behave in a class Why It Matters? Whenever you use: @property 👉 You’re already using descriptors under the hood. Yes — even Django models rely heavily on descriptors. Example: class Descriptor: def __get__(self, instance, owner): print("Getting value") return instance._value def __set__(self, instance, value): print("Setting value") instance._value = value class MyClass: attr = Descriptor() obj = MyClass() obj.attr = 10 # calls __set__ print(obj.attr) # calls __get__ What’s Happening Internally? When you do: obj.attr Python does NOT directly fetch the value. 👉 It checks: Does attr have __get__? If yes → call descriptor logic Real-World Use Cases Descriptors are used in: ✅ @property (getter/setter logic) ✅ Django ORM fields (models.CharField) ✅ Data validation frameworks ✅ Lazy loading attributes ✅ Caching values Example (Validation): class PositiveNumber: def __set__(self, instance, value): if value < 0: raise ValueError("Must be positive") instance.__dict__['value'] = value def __get__(self, instance, owner): return instance.__dict__.get('value', 0) class Product: price = PositiveNumber() p = Product() p.price = 100 # ✅ p.price = -10 # ❌ Error 👉 Clean validation without cluttering your class. Have you ever used descriptors directly, or only via @property? #Python #AdvancedPython #OOP #Django #SoftwareEngineering #BackendDevelopment #infosys #citi #SoftwareDevelopment

To view or add a comment, sign in

Explore content categories