Definition
A class variable belongs to the class and is shared by all its objects. An instance variable belongs to one object and is set through self. Reading looks on the object first and then on the class.
In simple words
Every student in a school shares the same school name, a class variable. Each has their own roll number, an instance variable.
Why it matters
Mixing them up causes a famous bug: a list stored as a class variable gets shared, so adding to one object's list changes everyone's.
How it works
In code
class Student:
school = "Pathshala" # class variable: shared
shared_marks = [] # the trap
def __init__(self, name):
self.name = name # instance variable: one per object
self.marks = []
a = Student("Riya")
c = Student("Aman")
print(a.school, c.school)
a.marks.append(90)
print(a.marks, c.marks)
a.shared_marks.append(90)
print(a.shared_marks, c.shared_marks) # both changed
Student.school = "New School"
print(a.school)
a.school = "Mine only" # now hides the class variable, on a only
print(a.school, c.school)Output
Pathshala Pathshala [90] [] [90] [90] New School Mine only New School
Common mistakes
- Putting items = [] at class level and expecting one list per object.
- Assigning self.count += 1 to update a shared counter. It creates an instance variable. Write Student.count += 1.
Check yourself
Summary
- Class variables are shared, and instance variables are per object.
- Create mutable data in __init__.
Finished reading?
Sources: The Python Tutorial, python.org