Object-Oriented Programming
Understanding Class Variables in Python: Part 2
Class variables are shared among all instances of a class, while instance variables are unique to each instance.
Ryan McBride
Ryan McBride
alt

Source: Sven Brandsma on Unsplash

Key Differences and Accessing Class Variables

Expansion: Until now, we've primarily focused on instance variables, which are unique to each individual object (instance) created from a class. Think of them as personal belongings—each person has their own unique set.

Class variables, on the other hand, are attributes that belong to the class itself, not to any specific instance. They are shared among all instances of that class. Imagine them as shared resources or universal facts about a category. For example, if you have a Car class, number_of_wheels (assuming it's always 4) would be a good candidate for a class variable because all cars generally have the same number of wheels.

Key Differences Summarized:

Feature Instance Variables Class Variables
Ownership Owned by individual instances. Owned by the class itself.
Scope Unique to each instance. Shared by all instances of the class.
Definition Defined inside methods (usually __init__) using self.attribute_name. Defined directly within the class body, outside any methods.
Purpose Store data unique to each object. Store data common to all objects of the class, or class-wide constants/counters.