Understanding the difference between a class variable and an instance variable can be a challenge for students. An instance variable is a variable that is defined inside a method and belongs only to the current instance of a class. A class variable is a variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class’s methods.
In the class Horse, color, breed, and gender are instance variables. They are “owned” by each particular instance. Each horse instance has its own breed, color, and gender.
In the class Horse, herd_size is a class variable. Each Horse instance does not have its own herd_size, it is shared by all instances of the class. After creating several instances of Horse, the value of the herd_size is changed because it is increased by 1 every time when we call the __init__ method (we create a new Horse instance thereby adding another horse to the herd). (See code below).
class Horse: herd_size = 0 ## This is a class variable def __init__(self, color="sorrel"): Horse.herd_size += 1 self.color = color self.breed = "unknown" self.gender = None
In Python, when modifying a class variable through an instance, a new (local) copy of the variable is created instead. See Classes – Python Syntax.