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 @property on a method function?
Asked
Active
Viewed 2,029 times
17
Andreas Jung
- 1
- 19
- 73
- 119
mkelley33
- 4,980
- 8
- 45
- 70
-
Why is a property a descriptor? – Tim Jun 29 '17 at 02:54
3 Answers
9
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.
XORcist
- 4,188
- 21
- 31
-
Thank you! So essentially you can split out responsibilities of the descriptor from the class that instantiates the descriptor?! Brilliant! – mkelley33 Apr 30 '11 at 15:37
-
1The possibilities are literally infinite ;) Think things like deferred loading: set a string of something you want loaded later on when first accessing the descriptor and never have to worry about that again. Or remove clutter from the owner class and put it where it logically belongs. – XORcist Apr 30 '11 at 15:50
-
@möter *set a string of something you want loaded later* You can do the same using `@property`, don't you? – Piotr Dobrogost Oct 11 '12 at 20:07
-
@PiotrDobrogost sure you can. But it would take at least another statement to do that,right? – XORcist Oct 12 '12 at 11:18
-
-
A descriptor can return a callable which can then be called, including instance methods. https://docs.python.org/3/howto/descriptor.html#descriptor-protocol – XORcist Apr 09 '20 at 10:47
4
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.
Sergei Danielian
- 4,731
- 4
- 33
- 57
-1
@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().
Andreas Jung
- 1
- 19
- 73
- 119
-
3Why would I prefer property over something like ``@my_method_name.setter``? Also, how does this apply to the concept of a custom-defined descriptor class? – mkelley33 Apr 30 '11 at 15:25