Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 357
jruota Avatar asked Mar 31 '17 18:03

jruota


People also ask

What is the purpose of class attribute Python?

A class attribute is a Python variable that belongs to a class rather than a particular object. It is shared between all the objects of this class and it is defined outside the constructor function, __init__(self,...) , of the class.

What is a property attribute in Python?

In python, everything is an object. And every object has attributes and methods or functions. Attributes are described by data variables for example like name, age, height etc. Properties are special kind of attributes which have getter, setter and delete methods like __get__, __set__ and __delete__ methods.

What is the purpose of attributes in objects Python?

Attributes of a class are function objects that define corresponding methods of its instances. They are used to implement access controls of the classes. Attributes of a class can also be accessed using the following built-in methods and functions : getattr() – This function is used to access the attribute of object.

What is the purpose of making class attributes private?

A private attribute provides you a level of protection from the users of your class, for that attribute. If you use a public attribute, you will need to add in more logic to test for invalid values up front, which can be more work, as well as more computationally expensive.


1 Answers

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.

like image 75
DevLounge Avatar answered Oct 02 '22 18:10

DevLounge