If you're a beginner in the world of object-oriented programming, you've probably faced the same doubt I did: class variables vs instance variables. Wait, wait, don't stop reading! I'm not here to dump theory like the big websites do or overload you with definitions. I want to clarify one specific concept about class and instance variables that has also confused me.
A class variable is a variable defined in the class but outside the constructor or any methods. Every object shares the same memory for this variable, so its value remains the same for all objects.
An instance variable, on the other hand, is an attribute defined inside methods or the constructor. Each object gets its own copy of it.
Take a look at the little program I wrote:
class Car:
base_price = 2000
def __init__(self, brand, model, year):
self.brand = brand
self.model = model
self.year = year
car1 = Car("apple", "icar, 2025)
print(car1)
print(car1.brand)
print(Car.base_price)
car1.base_price = 20000
print(Car.base_price)
print(car1.base_price)
Here's what I expected: when we print Car.base_price, it should show 2000. Then, when I changed base_price from 2000 to 20000, since class variables share memory space, I assumed the change would apply to all objects, even when accessed through the class name.
But that's not what happened. print(Car.base_price) still showed 2000, while print(car1.base_price) showed 20000. What the heck is going on?
Here's what's really happening: when we access a class variable using an object, Python first checks whether that object already has an instance variable with the same name. If it doesn't, it looks up to the class and uses the class variable.
But when we assign a value to that variable through the object, Python doesn't modify the class variable.
Instead, it quietly creates a new instance variable inside that object and stores the new value there. The original class variable remains unchanged.
That's why car1.base_price shows 20000 (it's now using the instance variable), while Car.base_price still shows 2000 (the class variable stayed the same). So the confusion comes from Python creating a new instance variable on that object without changing the class variable. When you assign through the object. It looks like you're changing the class variable, but you're actually just creating a brand-new variable that belongs only to that object.
If you want to change the value of a class variable, use the ClassName.classvariable syntax.
Top comments (0)