Instance vs Class Variables in Python
In Python classes, instance variables and class variables are used for different kinds of data.
- Use an instance variable for data that belongs to one object
- Use a class variable for data shared by all objects of the class
This page explains:
- what each one means
- when each one is created
- how Python finds them
- common beginner mistakes
Quick example
class Dog:
species = "Canis familiaris" # class variable
def __init__(self, name):
self.name = name # instance variable
a = Dog("Max")
b = Dog("Bella")
print(a.species)
print(b.species)
print(a.name)
print(b.name)
Output:
Canis familiaris
Canis familiaris
Max
Bella
Use a class variable for shared data. Use an instance variable for data that should be different for each object.
What this page teaches
- What instance variables are
- What class variables are
- How they are different
- How to choose the right one
What is an instance variable?
An instance variable belongs to one object.
It is usually created with self.variable_name inside __init__. If you are new to this, see the __init__ method in Python explained.
Example:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
dog1 = Dog("Max", 5)
dog2 = Dog("Bella", 3)
print(dog1.name)
print(dog2.name)
Output:
Max
Bella
Here:
self.nameis an instance variableself.ageis also an instance variable- each object gets its own values
If you change one object's instance variable, the other objects do not change.
dog1.name = "Rocky"
print(dog1.name)
print(dog2.name)
Output:
Rocky
Bella
What is a class variable?
A class variable belongs to the class itself.
It is defined inside the class, but outside methods.
Example:
class Dog:
species = "Canis familiaris"
def __init__(self, name):
self.name = name
dog1 = Dog("Max")
dog2 = Dog("Bella")
print(Dog.species)
print(dog1.species)
print(dog2.species)
Output:
Canis familiaris
Canis familiaris
Canis familiaris
Here:
speciesis a class variable- it is shared by all
Dogobjects - both objects can read it
Class variables are useful for:
- constants
- shared settings
- values that should be the same for every object
If you need a refresher on classes and objects, see Python classes and objects explained or what is a class in Python.
Main difference at a glance
The difference is simple:
- Instance variable: one value per object
- Class variable: one shared value on the class
Typical uses:
- instance variables:
name,age,price,file_path - class variables:
species,app_name,tax_rate,counter
Example:
class Product:
store_name = "Python Shop" # class variable
def __init__(self, name, price):
self.name = name # instance variable
self.price = price # instance variable
p1 = Product("Keyboard", 50)
p2 = Product("Mouse", 25)
print(p1.store_name)
print(p2.store_name)
print(p1.name, p1.price)
print(p2.name, p2.price)
How Python looks up variables
When you write obj.variable_name, Python does not only check the object.
Python looks in this order:
- first, it checks the object for an instance variable
- if it does not find one, it checks the class
This is why objects can read class variables.
Example:
class Example:
value = 100 # class variable
obj = Example()
print(obj.value)
Output:
100
obj does not have its own value, so Python gets value from the class.
Now look at this:
class Example:
value = 100
obj = Example()
obj.value = 200
print(obj.value)
print(Example.value)
Output:
200
100
What happened?
obj.value = 200created an instance variable- it did not change the class variable
- the instance variable now hides the class variable for that object
This idea becomes easier once you are comfortable with what is an object in Python.
When to use instance variables
Use instance variables when each object should store its own data.
Good examples:
- name
- age
- price
- file path
Example:
class User:
def __init__(self, username, email):
self.username = username
self.email = email
u1 = User("anna", "anna@example.com")
u2 = User("ben", "ben@example.com")
print(u1.username, u1.email)
print(u2.username, u2.email)
This is the best choice for values that are different from one object to another.
When to use class variables
Use class variables when the value should be shared.
Good examples:
- default tax rate
- app name
- category
- object counter
Example:
class Account:
bank_name = "Python Bank"
def __init__(self, owner):
self.owner = owner
a1 = Account("Ava")
a2 = Account("Noah")
print(Account.bank_name)
print(a1.bank_name)
print(a2.bank_name)
If the data should be different for each object, do not use a class variable.
Common beginner mistake: mutable class variables
Be careful with mutable values like:
- lists
- dictionaries
- sets
If you put one of these in a class variable, all objects share the same value.
Example of the problem:
class Student:
grades = [] # class variable
def __init__(self, name):
self.name = name
s1 = Student("Ava")
s2 = Student("Noah")
s1.grades.append(95)
print(s1.grades)
print(s2.grades)
Output:
[95]
[95]
Both objects show the same list because there is only one shared class variable.
If each object should have its own list, create it as an instance variable instead:
class Student:
def __init__(self, name):
self.name = name
self.grades = [] # instance variable
s1 = Student("Ava")
s2 = Student("Noah")
s1.grades.append(95)
print(s1.grades)
print(s2.grades)
Output:
[95]
[]
If this topic feels confusing, it helps to understand mutability in Python: mutable vs immutable types.
Common beginner mistake: changing through the object
Reading a class variable through an object is fine:
class Car:
wheels = 4
car = Car()
print(car.wheels)
But assigning through the object can create a new instance variable:
class Car:
wheels = 4
car1 = Car()
car2 = Car()
car1.wheels = 6
print(car1.wheels)
print(car2.wheels)
print(Car.wheels)
Output:
6
4
4
Important:
car1.wheels = 6did not change the class variable- it created an instance variable only on
car1 car2still reads the value from the class
If you want to change the shared value, change it on the class:
class Car:
wheels = 4
car1 = Car()
car2 = Car()
Car.wheels = 6
print(car1.wheels)
print(car2.wheels)
print(Car.wheels)
Output:
6
6
6
Simple rule to remember
- Shared by all objects = class variable
- Unique to each object = instance variable
Common causes of confusion
These are the most common reasons beginners mix them up:
- Using a class variable for data that should be unique per object
- Creating
self.variable_nameand thinking it changes the class variable - Using a mutable class variable like
[]or{}by mistake - Not understanding that objects can read values from the class
Useful debugging checks
If you are not sure where a variable is stored, these checks can help:
print(obj.__dict__)
print(ClassName.__dict__)
print(obj.variable_name)
print(ClassName.variable_name)
print(hasattr(obj, 'variable_name'))
What they do:
obj.__dict__shows the instance variables on that objectClassName.__dict__shows attributes on the classobj.variable_nameshows what Python finds when looking through the objectClassName.variable_namereads directly from the classhasattr(obj, 'variable_name')checks whether the object can access that name
Example:
class Dog:
species = "Canis familiaris"
def __init__(self, name):
self.name = name
dog = Dog("Max")
print(dog.__dict__)
print(Dog.__dict__['species'])
Output:
{'name': 'Max'}
Canis familiaris
This shows:
nameis stored on the objectspeciesis stored on the class
FAQ
Can an object access a class variable?
Yes. If the object does not have an instance variable with that name, Python reads the value from the class.
Can a class variable be changed?
Yes. Change it on the class when you want the shared value to update for all objects.
Why did changing a class variable on one object only affect that object?
You likely created a new instance variable with the same name instead of changing the variable on the class.
Should I put lists and dictionaries in class variables?
Only if you want all objects to share the same list or dictionary. Otherwise use an instance variable.