When and why might I assign an instance of a descriptor class to a class attribute in Python rather than use a property?

*爱你&永不变心* 提交于 2019-11-28 23:24:17

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.

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.

@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().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!