Class Variables and Shared Data
Explore the concept of class variables in Python and understand how they store data shared among all instances of a class. Learn to distinguish between instance and class variables, manage shared counters, and avoid shadowing bugs by updating class variables correctly through the class name. This lesson helps you design efficient object-oriented programs by separating individual object data from shared class-level data.
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 ...