Classes and OOP I

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:

Python

Every Dog instance can read the shared species attribute:

Python
Output

What will be the output?

Python

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:

Python
Output

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:

Python
Output

What will be the output?

Python

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:

Python
Output

What will be the output?

Python

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:

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python