Descriptors & Properties
Expert Answer & Key Takeaways
Mastering Descriptors & Properties is essential for high-fidelity technical performance and advanced exam competency in 2026.
Descriptors & Properties: The Mechanics of Attribute Access (2026)
Descriptors are the low-level mechanism behind
@property, classmethod, and staticmethod. They are objects that define the behavior of attribute access (Get, Set, Delete) for other objects.1. The Proof Code (Validation Descriptor)
class PositiveInteger:
"""A descriptor that enforces positive integer values."""
def __set_name__(self, owner, name):
# Stores the name of the attribute on the owner class
self.name = name
def __get__(self, instance, owner):
if instance is None: return self
return instance.__dict__.get(self.name)
def __set__(self, instance, value):
if not isinstance(value, int) or value < 0:
raise ValueError(f"{self.name} must be a positive integer")
instance.__dict__[self.name] = value
class Product:
price = PositiveInteger()
stock = PositiveInteger()
if __name__ == "__main__":
p = Product()
p.price = 100
# p.price = -10 # Raises ValueError
print(f"Price: {p.price}")
# Output:
# Price: 1002. Execution Breakdown
- The Descriptor Protocol: Any object that implements
__get__,__set__, or__delete__is a descriptor. It must be defined as a Class Attribute on the owner class. - Data vs. Non-Data Descriptors:
- Data Descriptors implement both
__get__and__set__. They always take precedence over the instance dictionary. - Non-Data Descriptors implement only
__get__. They can be overridden by an entry in the instance's__dict__.
- Data Descriptors implement both
- Interception: When you write
obj.x, Python checks ifxis a descriptor in the class. If it is, it callstype(obj).x.__get__(obj, type(obj))instead of looking inobj.__dict__. - The Property Decorator:
@propertyis simply a high-level wrapper around the descriptor protocol, creating a data descriptor for you automatically.
3. Detailed Theory
Descriptors are the 'secret sauce' that makes Python's attribute system so flexible.
The Lookup Chain
When you access
obj.attr, Python searches in this order:- Data Descriptor in the class (and its parents).
- Instance
__dict__. - Non-Data Descriptor in the class.
- Class
__dict__. __getattr__method (if it exists).
Why use Descriptors?
- Validation: Enforce rules for multiple attributes across different classes (like our
PositiveIntegerexample) without repeating@propertyboilerplate. - Lazy Loading: Calculate an attribute value only when it's first accessed and then cache it in the instance dictionary.
- Bound Methods: Every function in Python is a descriptor. When you access
obj.method, the function's__get__method returns a 'bound method' object that pre-fills theselfargument.
[!TIP] Senior Secret: Use__set_name__(introduced in 3.6) to automatically capture the attribute name from the class definition. This eliminates the need to pass the name (e.g., "price") manually into the descriptor's constructor, making your code cleaner and less error-prone.
Top Interview Questions
?Interview Question
Q:What is the difference between a Data and Non-Data descriptor?
A:
A Data Descriptor implements
__set__ and has higher precedence than the instance dictionary. A Non-Data Descriptor only implements __get__ and can be overridden by a variable in the instance dictionary.?Interview Question
Q:Where must a descriptor be defined?
A:
A descriptor must be defined as a Class Attribute, not an instance attribute. It acts as a shared 'manager' for that attribute across all instances of the class.
?Interview Question
Q:How does @property relate to descriptors?
A:
@property is a built-in class that implements the descriptor protocol. It maps attribute access to the getter, setter, and deleter functions you define.Course4All Engineering Team
Verified ExpertData Science & Backend Engineers
The Python curriculum is designed by backend specialists and data engineers to cover everything from basic logic to advanced automation and API design.
Pattern: 2026 Ready
Updated: Weekly
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.