When working with Python classes, a common point of confusion is the difference between instance variables and class variables.
They may look similar, but they behave very differently.
In this short and clear guide for Python Class vs Instance Variables, we’ll break down:
- What instance and class variables are
- How they’re declared and used
- How they behave across different objects
- Visual examples to understand the difference
- Common mistakes to avoid
Let’s begin.
🧍 What Is an Instance Variable?
An instance variable belongs to a specific object.
It is created inside the __init__() method using self:
class Student:
def __init__(self, name):
self.name = name # instance variableEvery time you create a new Student, it gets its own name.
s1 = Student("Ali")
s2 = Student("Fatima")
print(s1.name) # Ali
print(s2.name) # Fatima✅ Each object has its own copy of the variable.
🏫 What Is a Class Variable?
A class variable is shared by all objects of the class.
It is defined outside of any method, directly inside the class.
class Student:
school = "PyUniverse" # class variable
def __init__(self, name):
self.name = nameNow:
s1 = Student("Ali")
s2 = Student("Fatima")
print(s1.school) # PyUniverse
print(s2.school) # PyUniverse✅ Every object shares the same value unless it’s overridden.
🧠 Visual Comparison
| Feature | Instance Variable | Class Variable |
|---|---|---|
| Scope | Specific to each object | Shared across all objects |
| Defined in | __init__() with self.var | Inside class, outside any method |
| Memory | Separate copy per object | One copy shared by class and all objs |
| Modified using | self.var = value | ClassName.var = value (preferred) |
⚠️ Common Mistakes
❌ Mistake 1: Modifying Class Var via self
s1.school = "AnotherSchool"You might think this changes the class variable for all objects…
But it actually creates a new instance variable only for s1.
✅ To change it for all objects:
Student.school = "AnotherSchool"🧪 Real-World Analogy
Class Variable = Common across all students (e.g., school name)
Instance Variable = Unique to each student (e.g., their name, roll number)