Variables declared at the “top level” in a class are attributes of the class–the same variable is common to all instances. Class variables are most commonly referenced using dot notation with the class name, e.g., Horse.herd_size
(see below). The variable can also be referenced through an instance, however, assigning this variable a value in this way creates a new copy of that variable local to the instance. This feature in Python can be confusing, especially for students familiar with Java or C++.
For example, we can modify the Horse
class to keep track of the herd size by introducing a class variable, herd_size
:
class Horse: herd_size = 0 def __init__(self, color="sorrel"): Horse.herd_size += 1 self.color = color self.breed = "unknown" self.gender = None
After creating several instances of Horse
, we can access the herd_size
variable to see how many there are:
silver = Horse("white") trigger = Horse("palomino") wilbur = Horse("palomino") buck = Horse("buckskin") secretariate = Horse() print(Horse.herd_size)
prints 5.
We can access the class variable through an instance, for example:
print(silver.herd_size)
also prints 5. However, if we attempt to modify the variable through an instance, a new (local) copy of the variable is created instead:
silver.herd_size = 0; print(silver.herd_size) print(Horse.herd_size) sea_biscuit = Horse() print(trigger.herd_size)
prints 0, 5, 6. The object referenced by silver now has a local copy of the herd_size
variable, but the Horse
class variable is unaffected, as are instances of Horse
that have not created their own local copies.