Search code examples
pythondescriptor

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 @property on a method function?


Solution

  • 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.