Some text some message..
Back 🎨 Instance Variable vs Class Variable in Python 19 Sep, 2025

1️⃣ Class Variables (Shared across all objects)

  • Belong to the class itself.

  • Stored in class memory space (not inside each object).

  • Shared by all objects of that class.

  • Changing class variable using the class name → affects all objects.

  • Changing class variable using an object → creates an instance variable for that object only.

💡 Analogy: Think of a school name – all students share the same school name.


2️⃣ Instance Variables (Unique for each object)

  • Belong to the object (instance).

  • Stored in object’s memory.

  • Each object has its own copy.

  • Changing one object’s instance variable does not affect others.

💡 Analogy: Think of a student’s roll number – each student has their own unique roll number.


🐍 Python Example

class Student:
    # 🎓 Class Variable (shared by all students)
    school_name = "ABC International School"

    def __init__(self, name, roll):
        # 🧍 Instance Variables (unique to each student)
        self.name = name
        self.roll = roll


# Creating objects (instances)
s1 = Student("Abhi", 101)
s2 = Student("Ivan", 102)

# Access class variable
print(s1.school_name)   # ABC International School
print(s2.school_name)   # ABC International School

# Access instance variables
print(s1.name, s1.roll) # Abhi 101
print(s2.name, s2.roll) # Ivan 102

# 🎨 Changing class variable using class name
Student.school_name = "XYZ Global School"

print(s1.school_name)   # XYZ Global School
print(s2.school_name)   # XYZ Global School

# 🎨 Changing class variable using object
s1.school_name = "Local School"

print(s1.school_name)   # Local School (but now it's an instance variable for s1)
print(s2.school_name)   # XYZ Global School
print(Student.school_name) # XYZ Global School

🌈 Visualization

🔹 Class Variable (Shared)

Student.school_name → "XYZ Global School"

All objects (s1, s2) point to the same value unless overridden.

🔹 Instance Variables (Unique)

s1.name → "Abhi"
s1.roll → 101

s2.name → "Ivan"
s2.roll → 102

Each object has its own copy.


📌 Key Differences Table

Feature Class Variable 🏫 Instance Variable 🧍
Belongs to Class (shared by all objects) Specific object
Memory location Class namespace Object namespace
Shared? Yes No (unique per object)
Change via class Affects all objects N/A
Change via object Creates new instance variable Affects only that object

Summary:

  • Use class variables when you want a common property across all objects.

  • Use instance variables when each object should maintain its own state.