When And Why Might I Assign An Instance Of A Descriptor Class To A Class Attribute In Python Rather Than Use A Property?
I'm aware that a property is a descriptor, but are there specific examples of when using a descriptor class might be more advantageous, pythonic, or provide some benefit over using
Solution 1:
Better encapsulation and re-usability: A descriptor class can have custom attributes set on instantiating. Sometimes it's useful to keep data confined in this manner, instead of having to worry about it getting set or overwritten on the descriptor's owner.
Solution 2:
Let me quote from the EuroPython 2012 great video "Discovering Descriptors":
How to choose between descriptors and properties:
- Properties work best when they know about the class
- Descriptors are more general, can often apply to any class
- Use descriptors if behaviour is diferent for classes and instances
- Properties are syntactic sugar
Also, please note, you can use __slots__
with Descriptors.
Solution 3:
@property does not allow you to define dedicated setter and getter methods at the same time. If a getter method is "good enough" then use @property otherwise you need property().
Post a Comment for "When And Why Might I Assign An Instance Of A Descriptor Class To A Class Attribute In Python Rather Than Use A Property?"