Why should properties be class attributes in Python?

I recently learned about managed attributes in Python, and the common theme with properties and descriptors is that they should be assigned as class attributes. But nowhere can I find an explanation of why and especially why they cannot be assigned as attributes of an instance. So my question has two parts:

  • Why should property / descriptor instances be class attributes?
  • Why are property / descriptor instances not instance attributes?
+7
python properties
source share
2 answers

This is due to the way Python tries to resolve attributes:

  • It first checks to see if it is defined at the class level.
  • If yes, it checks if this is a property or data descriptor
  • If yes, then this "path" follows
  • If not, it checks to see if it is a simple class variable (to its parent classes, if any)
  • If yes, it checks that the instance overrides this class attribute value; if so, it returns an override value if it does not return the class attribute value
  • If not, it checks if this attribute declares this attribute
  • If so, it returns the value of the instance attribute
  • If not, it throws an AttributeError

Voila; -)

EDIT

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

Another nice illustration .

+3
source share

why should property / descriptor instances be class attributes?

They don’t have to be, they just are. It was a constructive solution, which probably has many more reasons for backing it up than I can think of (simplifying the implementation, separating classes from objects).

Why are property / descriptor instances not instance attributes?

They may be, you can always override __getattribute__ to call any descriptors available on the instance, or even prohibit them if you want.

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

0
source share

All Articles