Class Variables and Shared Data
Explore how class variables enable shared data management among multiple objects of a class in Python. Understand the difference between instance and class variables, how to properly update shared state using the class name, and avoid common issues such as shadowing. This lesson helps you design clean, maintainable classes that separate individual object identities from global configurations or statistics.
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 ...