Class Variable and Instance Variable

Python classes can hold two kinds of variables: class variables, which are shared across every object of that class, and instance variables, which hold unique data for each individual object.

Instance Variables

Instance variables are typically defined inside the __init__ method using self, and each object gets its own separate copy.

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

s1 = Student("Abhay")
s2 = Student("Priya")
print(s1.name, s2.name)   # Abhay Priya (different for each object)

Class Variables

Class variables are defined directly inside the class body, outside any method, and their value is shared by every instance of the class unless explicitly overridden.

class Student:
    institute = "Uncodemy"   # class variable, shared by all students

    def __init__(self, name):
        self.name = name   # instance variable, unique per student

s1 = Student("Abhay")
s2 = Student("Priya")
print(s1.institute, s2.institute)   # Uncodemy Uncodemy
Changing a class variable through the class itself (e.g. Student.institute = "New Name") updates it for all instances, whereas assigning it through a specific instance creates a new instance variable that shadows the class variable just for that object.

Coming Up Next

Next, you'll learn about constructors and destructors - the special methods that run automatically when an object is created and destroyed.

How Python Looks Up an Attribute

When you write obj.attr, Python searches in a fixed order. First it checks the object's own namespace, stored in obj.__dict__. If the name is not there, it checks the class, and then any parent classes. This lookup order is the reason a class variable appears to "belong" to every object, and also the reason an instance assignment can hide it.

class Counter:
    total = 0          # class variable

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

a = Counter("a")
print(a.__dict__)        # {'label': 'a'}
print(Counter.__dict__["total"])  # 0

a.total = 5              # creates a NEW instance variable on a
print(a.__dict__)        # {'label': 'a', 'total': 5}
print(Counter.total)     # 0  (class value unchanged)

Printing __dict__ is a quick debugging trick whenever you are unsure which value an object is really using.

Worked Example: Counting Objects Correctly

A classic use of a class variable is a counter shared by all instances. The important detail is to update it through the class name, not through self.

class Order:
    count = 0
    tax_rate = 0.18

    def __init__(self, amount):
        self.amount = amount
        Order.count += 1          # correct: updates the shared value

    def total(self):
        return self.amount * (1 + self.tax_rate)

o1 = Order(100)
o2 = Order(250)
print(Order.count)     # 2
print(o2.total())      # 295.0

If you wrote self.count += 1 instead, each object would read the class value, add one, and store the result on itself. The shared counter would stay at zero.

The Mutable Class Variable Trap

Using a list or dictionary as a class variable is one of the most common beginner bugs. Because the list object is shared, appending through one instance changes it for all of them.

class Team:
    members = []                 # shared by every Team!

    def add(self, name):
        self.members.append(name)

t1, t2 = Team(), Team()
t1.add("Asha")
print(t2.members)   # ['Asha']  surprising

class SafeTeam:
    def __init__(self):
        self.members = []        # each object gets its own list

Notice that append does not assign a new name, so no shadowing happens. The fix is to create mutable data inside __init__.

Class Variables and Inheritance

Subclasses inherit class variables from their parent, and they can override them simply by defining the same name in their own body. The parent keeps its original value, so each class in the hierarchy can carry its own default. This makes class variables a clean place for settings that vary by type, such as a discount rate for a premium customer class versus a regular one.

When a method needs to change shared state, a @classmethod is often clearer than writing the class name by hand. It receives the class as cls, so a subclass that calls it updates its own value rather than the parent's.

Choosing Between the Two

Use a class variable forUse an instance variable for
Constants shared by all objects, such as a default rateData that differs per object, such as a name or balance
Counters or registries of all instancesLists and dictionaries owned by one object
Configuration that subclasses may overrideState that changes during the object's life

Quick checklist: read shared values through self if you like, but write them through the class name; never use a mutable class variable unless sharing is intended; and inspect __dict__ when values look wrong.

Ready to Master Data Science?

Join Uncodemy's Data Science Course and build real, job-ready skills with expert mentors.

Explore Course