Instance vs Class Variables in Python A Clear Visual Guide

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:

Python
class Student:
    def __init__(self, name):
        self.name = name  # instance variable

Every time you create a new Student, it gets its own name.

Python
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.

Python
class Student:
    school = "PyUniverse"  # class variable

    def __init__(self, name):
        self.name = name

Now:

Python
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

FeatureInstance VariableClass Variable
ScopeSpecific to each objectShared across all objects
Defined in__init__() with self.varInside class, outside any method
MemorySeparate copy per objectOne copy shared by class and all objs
Modified usingself.var = valueClassName.var = value (preferred)

⚠️ Common Mistakes

❌ Mistake 1: Modifying Class Var via self

Python
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:

Python
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)


💌 Stay Updated with PyUniverse

Want Python and AI explained simply straight to your inbox?

Join hundreds of curious learners who get:

  • ✅ Practical Python tips & mini tutorials
  • ✅ New blog posts before anyone else
  • ✅ Downloadable cheat sheets & quick guides
  • ✅ Behind-the-scenes updates from PyUniverse

No spam. No noise. Just useful stuff that helps you grow one email at a time.

🛡️ I respect your privacy. You can unsubscribe anytime.

Leave a Comment