7

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?

2 Answers 2

3

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

  1. First it checks if it is defined at the class level
  2. If yes, it checks if it is a property or a data descriptor
  3. If yes, it follows this "path"
  4. If no, it checks if it is a simple class variable (up to its parent classes if any)
  5. 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
  6. If no, it checks if the instance declares this attribute
  7. If yes, it returns the instance attribute value
  8. If no, it throws AttributeError

Voila ;-)

EDIT

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

Another nice illustration.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.