Why do properties have to be class attributes in Python?

Recently I have been learning about managed attributes in Python and a common theme with properties and descriptors is, that they have to be assigned as class attributes. But nowhere can I find an explanation of why and especially why they cannot be assigned as instance attributes. So my question has actually two parts:

  • why do properties / descriptor instances have to be class attributes?
  • why can properties / descriptor instances not be instance attributes?

  • It is because of the way Python tries to resolve attributes:

  • First it checks if it is defined at the class level
  • If yes, it checks if it is a property or a data descriptor
  • If yes, it follows this "path"
  • If no, it checks if it is a simple class variable (up to its parent classes if any)
  • If yes, it checks the instance overrides this class attribute value, if yes, it returns the overriden value, if no it returns the class attribute value
  • If no, it checks if the instance declares this attribute
  • If yes, it returns the instance attribute value
  • If no, it throws AttributeError
  • Voila ;-)

    EDIT

    I just found this link which explains it better than me.

    Another nice illustration.


    why do properties/descriptor instances have to be class attributes?

    They don't have to be, they just are. This was a design decision that probably has many more reasons to back it up than I can think (simplifying implementation, separating classes from objects).

    why can properties/descriptor instances not be instance attributes?

    They could be, you can always override __getattribute__ in order to invoke any descriptors accessed on an instance or forbid them altogether if you desire.

    Keep in mind that the fact that Python won't stop you from doing this doesn't mean it's a good idea.

    链接地址: http://www.djcxy.com/p/38816.html

    上一篇: 如何使用Azure Active Directory PowerShell V2“授予权限”

    下一篇: 为什么属性必须是Python中的类属性?