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:
It is because of the way Python tries to resolve attributes:
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中的类属性?