What’s a class attribute?
Class attributes are attributes which are owned by the class itself. They will be shared by all the instances of the class. Therefore they have the same value for every instance.So 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’s an instance attribute?
Instance attributes are owned by the specific instances of a class. This means for two different instances the instance attributes are usually different.Therefore instance attribute is a Python variable belonging to one, and only one, object. This variable is only accessible in the scope of this object and it is defined inside the constructor function,
__init__(self,..) of the class.
This is a basic Python class with two attributes: class attribute and instance attribute.
- height and width are an instances attribute defined inside the constructor.
- number of instances is a class attribute defined outside the constructor.
The differences between class and instance attributes
On the one hand theclass attributes is shared by all instances. When you change the value of a class attribute, it will affect all instances that share the same exact value. On the other hand instance attributes is unique to only that instance.
Advantages of instance attributes
- They are specific to an object and are easy to set and get thanks to properties.
- They are discarded once the instance is deleted, so they die with the instance they are associated with, which makes things clearer.
Advantages of class attributes
- All instances of the class inherit them from the class.
- They store data that is relevant to all the instances. For example, we could have a counter class attribute that increments every time we create a new instance and decrements every time we delete an instance.
Disadvantages of instance attributes
- They don’t allow keeping track of values in between instances.
- The fact that their values are lost on deletion is also a disadvantage in some cases where you want to keep a history of values for example.
Disadvantages of class attributes
- It can get messy when you create an instance in which the value of the class attribute is different than the class attribute value, and then try to retrieve it through another instance
- If you want to change a class attribute, you have to do it with the notation ClassName.AttributeName. Otherwise, you will create a new instance variable.
Every object in Python has an attribute denoted by
__dict__. This dictionary is an object contains all the attributes defined for the object itself. It maps the attribute name to its value.
__dict__ of a class however, is not that straight-forward. Its actually an object of a class called
dictproxy is a special class whose objects behave like normal
dicts, but they differ in some key behaviours.