Class Variables and Shared Data
Explore the concept of class variables in Python to manage data shared among all instances of a class. Understand how class variables differ from instance variables, learn their proper use cases, and avoid common errors such as shadowing. This lesson helps you structure Python classes effectively by separating unique object data from shared state, enabling better management of collective attributes like counters and configuration settings.
So far, each object has been given its own identity. For example, when ten Spaceship objects are created, each instance has its own name and fuel_level. Not all data belongs to individual ships. Some information applies to the entire fleet. For example, a program may need to track the number of active ships or define a global shield frequency shared by all ships. Storing this information in each instance would be inefficient and error-prone because updates would require modifying every object. Python addresses this with class variables, which store shared data in one location that all instances can access.
Defining class variables
A class variable is defined directly inside the class body, outside of any methods (including __init__). While instance variables (self.variable) are tied to a specific object, class variables are stored on the class object itself.
This distinction is physical in memory. When we launch 100 ships, we have 100 copies of the instance variables, but still only one copy of the class variable.