Class and instance attributes

Olivier Guyot
3 min readJan 11, 2021

In python there is two main attribute the class attribute and the instance attribute.

The class Attribute

The classe attribute is an attribute own by a classe though there scope is limited by the class and all instance of the class will share the same class attribute.

It’ means If we create a class attribute every instance of this class will share the same attribute

How to create a classe attribute :

Define it outside of the function

A class attribute is defined outside of the constructor function __init__ of the class. One way to create a class attribute is to defined it at the begining of a class.

Example :

In that example, we have created a class attribute named : “classAttribute”. Every time we create a new instance of that class :” MyClass”. We will access to the class attribute.

An other methode is to use the dictionary __dict__. Python store every class and object attribute in a separate dictionary that we can access by using the statement __dict__.

How to modify a class attribute.

To modify a classe attribute we can simply change the value of the class attribute. And all the instance of that class will also be changed in one line of code.

Example :

Output :

By accessing directly to the class attribute we was able to modify it quickly.

How to modify an instance attribute

Output:

Here we try to change the instance attribute by the same way we did with the class attribute. And we seen that it doesn’t work. It confirm that a instance attribute is not shared between instances of a class.

The __dict__ method

An other method to interact with attribute is the __dict__ method

Ouput :

In that method attribute are stored in the dictionary. We access to the dictionary with the methode __dict__ and we modify the value with the key :<instanceAttribute>.

The getter and setter method

To assign a value to an attribute we can use the setter and getter method. Thus methode give the possibility to check the value before to assign them. For example we can use it to raise an exeption before assigning the value.

This method use Two decorator de @property and the @<variable>.setter

Example:

Here if the value is not an int a specific message will be displayed.

The difference :

The main difference between a classe attribut and an instance attribute is their scope. One is more general to a class and can be share between their instances. The other one is specified to an instances and not shared.

Thus difference make the class attribute can be easily change but the cons it’s not specified.

The instance attribute is specified but the cons is we can’t change all the instance of all the different object quickly.

Thank you for reading

--

--