Class Attributes
So far every attribute lived on an individual instance. Sometimes you want data that is shared across all instances of a class. That is what class attributes are for.
So far every attribute you created lived on a single instance. But sometimes a piece of data belongs to the class itself and should be shared by all instances.
A class attribute is defined directly in the class body, outside any method:
Every Dog instance can read the shared species attribute:
What will be the output?
You can also access a class attribute through the class name directly, without any instance.
Both ways work. Through the class or through an instance:
A class attribute can be updated through the class name. The change is visible to all instances.
Watch what happens when we change the class attribute:
What will be the output?
But setting an attribute through an instance creates a new instance attribute that shadows the class one. The class attribute stays unchanged.
Only a gets a new instance attribute. b still reads the class attribute:
What will be the output?
A common use case is counting how many instances have been created. The counter lives on the class so every new instance can update it.
Each __init__ call increments the shared counter:
What will be the output?
What will be the output?
What will be the output?