Lesson 4: Class Variables, Class Methods and Static Methods
So far every attribute we have created belonged to one instance: self.balance is different for every account. But sometimes a value belongs to the class as a whole. Imagine a school where every student pays the same annual fee, or a game where every enemy shares the same difficulty setting. Storing that value on every instance would waste space and, worse, let the copies drift apart when the value changes. A class variable is defined directly in the class body, outside any method, and is shared by all instances of the class.
The important subtlety is how Python looks a name up. When you read ana.fee, Python first checks the instance, and only then the class. When you assign ana.fee = 50, you create a brand-new instance attribute that shadows the class variable — the class value itself does not change, and other instances keep seeing the old one. That is the single most common class-variable bug, and the example below shows it happening on purpose. The rule to remember is simple: read a class variable through the instance if you like, but always write it through the class, as Student.fee = 60.
class Student:
fee = 100 # class variable: shared by all students
def __init__(self, name):
self.name = name
ana = Student("Ana")
ben = Student("Ben")
print(ana.fee, ben.fee) # 100 100
Student.fee = 120 # change it on the CLASS
print(ana.fee, ben.fee) # 120 120
ana.fee = 999 # creates an INSTANCE attribute on ana only
print(ana.fee, ben.fee) # 999 120
print(Student.fee) # 120 — the class value never moved
Class methods and static methods
Methods come in three flavours. A normal method receives the instance as self. A class method, marked with the @classmethod decorator, receives the class itself as cls instead — useful for alternative constructors, such as building a student from a data file, or for changing class-level state. A static method, marked with @staticmethod, receives neither the instance nor the class: it is just a regular function that happens to live inside the class because it belongs there logically, such as a helper that checks whether a student ID has the right format.
Choosing between them is a matter of what the method needs. If it touches instance data, it is a normal method. If it touches class data or needs to build an instance in a special way, it is a class method. If it needs neither but belongs to the class's job, it is a static method. A common pattern you will see in real code is a class method called from_dict or from_file that reads data and returns a new instance — a neat alternative constructor that keeps the messy parsing code inside the class where it belongs.
Going further
Class variables have one famous trap: a mutable class variable, such as a list or a dictionary, is shared by every instance — and if one instance mutates it, every instance sees the change. That is sometimes exactly what you want, for example a registry of all the objects ever created, but it is a frequent source of surprise. If each instance needs its own list, create it inside __init__ as an instance attribute. The rule of thumb is that immutable class variables (numbers, strings) are safe to share, while mutable ones should be shared only deliberately, with a comment explaining why.
Class methods shine as alternative constructors, and the pattern is worth practising. Imagine a Student that can be built from a line of a text file, such as "ana,100". A class method called from_record would split the line, convert the fee, and return cls(name) — using cls rather than the class name, so the method still works if a subclass calls it. That is the real advantage of cls over naming the class directly: the constructor stays correct for every subclass, without any extra code.
Here is a pattern you will see in real codebases: a class variable that counts how many instances have been created. Each __init__ increments ClassName.count by one, and a class method called total_created() returns it. It is a legitimate use of shared state — the count genuinely belongs to the class, not to any one instance — and it is a good test of whether you understand the difference between reading a class variable through an instance and writing one. Try implementing it for the Student class, then check that creating three students makes the count read three, and that no single student can change the count by assigning to its own attribute.
Watch & Learn
One video to watch for this unit, from a trusted educator.
- Python OOP Tutorial 2: Class Variables — Corey Schafer
Corey explains class variables and how they differ from instance variables, with examples of when each is the right choice.
Key Terms
- Class variable
- A variable defined in the class body and shared by all instances of the class.
- Instance variable
- A variable set on self, belonging to one particular instance.
- Shadowing
- Creating an instance attribute with the same name as a class variable, hiding the class value for that instance only.
- @classmethod
- A decorator marking a method that receives the class (cls) as its first argument instead of an instance.
- @staticmethod
- A decorator marking a method that receives neither the instance nor the class.
- cls
- The conventional name for the first parameter of a class method: the class itself.
- Alternative constructor
- A class method that builds an instance from a different kind of input, such as from_dict or from_file.
Discussion Questions
- Why is writing ana.fee = 999 so dangerous if you meant to change the fee for everyone? How would you catch this bug in a real program?
- When would a class variable be the wrong choice, even for a value that starts out the same for every instance?
- Think of a class method you would add to BankAccount. What would it construct, and what input would it take?
Practice Questions
- After
Student.fee = 120, what doesben.feeshow? - After
ana.fee = 999, what doesStudent.feeshow? - A method needs to read a class variable but no instance data. Which kind of method should it be?
- A helper checks whether a string looks like a valid student ID. It needs no instance or class data. Which decorator fits?
- Write a class method
from_namefor Student that takes a name and returns a new Student.
Show answers
- 120. Reading through the instance finds the class variable, which was changed on the class itself.
- 120. Assigning through the instance creates an instance attribute on ana only; the class variable is untouched.
- A class method. It receives cls, so it can reach class-level data without needing an instance.
- @staticmethod. The function belongs with the class logically but needs neither self nor cls.
@classmethod def from_name(cls, name): return cls(name)Using cls instead of the class name keeps the constructor working for subclasses too.