Class Variables vs Instance Variables
15 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)In Python, variables defined directly inside the class body belong to the class object, whereas variables assigned on self belong to the individual instance. Knowing how Python traverses __dict__ namespaces prevents subtle shared-state bugs.
Class Variables vs Instance Variables
Class variable is a name defined in the class body. It belongs to the class and is shared by all instances, unlike an instance variable set through self.
A class variable is shared by all instances of the class. An instance variable is unique to each individual object.
class Employee: company_name = "Acme Corp" # Class variable (shared)
def __init__(self, name): self.name = name # Instance variable (unique)
e1 = Employee("Aarav")e2 = Employee("Diya")print(e1.company_name, "|", e2.company_name)Example 1 · One shared setting, separate data
class Order: tax_rate = 18
def __init__(self, amount): self.amount = amount
def total(self): return self.amount + self.amount * self.tax_rate // 100
o1 = Order(1000)o2 = Order(500)print(o1.total(), o2.total())Order.tax_rate = 5print(o1.total(), o2.total())1180 590 1050 525
What this code does
tax_rateis stored once on the class, so changingOrder.tax_ratechanges it for every order.amountis stored on each object, so the two totals differ.
Both instances access company_name through the shared class blueprint.
Namespace Lookup (__dict__)
Attribute lookup is how Python finds obj.name: it checks the object's own dictionary first, then the class, then its parents, and stops at the first match.
When you access obj.attribute, Python first checks obj.__dict__. If not found, it searches Class.__dict__.
print(e1.__dict__) # {'name': 'Aarav'}print(Employee.__dict__["company_name"]) # Acme CorpExample 2 · Assigning on an instance shadows the class value
class Employee: company = "Acme Corp"
def __init__(self, name): self.name = name
e1 = Employee("Aarav")e2 = Employee("Diya")e1.company = "Beta Ltd"print(e1.company, e2.company, Employee.company)print("company" in e1.__dict__, "company" in e2.__dict__)Beta Ltd Acme Corp Acme Corp True False
What this code does
- The assignment creates a new entry in
e1.__dict__. The class value is untouched. e2has no owncompany, so lookup falls back to the class.
Example 3 · The += surprise
class Visits: count = 0
v1 = Visits()v1.count += 1print(v1.count, Visits.count)1 0
What this code does
v1.count += 1meansv1.count = v1.count + 1.- It reads the class value 0, then writes 1 on the instance. The class still holds 0.
If you assign e1.company_name = "New Corp", Python creates a new entry in e1.__dict__, shadowing the class attribute for e1 without altering e2 or Employee!
The Mutable Class Variable Trap
Mutable class variable is a list or dictionary created in the class body. Every instance reaches the same object, so a change through one instance shows in all.
If a class variable is mutable (like a list or dictionary), mutating it in-place via any instance mutates the shared object for all instances!
class BuggyCart: items = [] # CLASS VARIABLE - SHARED BY ALL!
c1 = BuggyCart()c2 = BuggyCart()c1.items.append("Laptop")print(c2.items) # ['Laptop']! BUG: c2 sees c1's itemExample 4 · The fix: create the list per object
class Cart: def __init__(self): self.items = []
c1 = Cart()c2 = Cart()c1.items.append("Laptop")print(c1.items)print(c2.items)['Laptop'] []
What this code does
__init__runs for each object, so each cart gets its own new list.- Appending to
c1.itemscannot reachc2.items.
Always initialize mutable collections inside __init__ on self so each instance owns an independent collection.
Legitimate Uses for Class Variables
Overview of Legitimate Uses for Class Variables:
Example 5 · Counting instances with a class variable
class Worker: total_workers = 0
def __init__(self, name): self.name = name Worker.total_workers += 1
w1 = Worker("Arjun")w2 = Worker("Sara")print("Total workers created:", Worker.total_workers)Total workers created: 2
What this code does
Worker.total_workersincrements each time__init__is executed.- The state is tracked cleanly on the class object.
Default configuration constants: e.g. TIMEOUT = 30, MAX_RETRIES = 3. Tracking instance counts: Incrementing cls.counter inside __init__. Precomputed lookup tables: Shared mapping tables used by all instances.
What's next
You finished the preview of Classes & Objects
Python Programming has 21 sections, 110 modules and 609 lessons. An account opens every lesson and saves your progress.
Next step
Check your understanding
12 quick questions