Learn Python
>>> oop_fundamentals.instance_class_vars

Instance Variables vs Class Variables in Python

#concept

An instance variable belongs to one specific object, set (usually inside __init__()) with self.name = value — every instance gets its own independent copy. A class variable belongs to the class itself, defined directly inside the class body outside any method, and is shared by every instance unless a particular instance overrides it.

#how it works
1

Instance variables use self

self.name = value, typically set inside __init__().

2

Each instance has its own copy

Instance variables are never shared between objects.

3

Class variables live in the class body

Written at the same indentation as method definitions, outside any method.

4

Class variables start out shared

Until one instance is given its own instance variable of the same name.

5

Assigning through an instance shadows, not shares

instance.variable = value creates a new instance variable rather than changing the class-wide one.

#example
class Dog:
species = "Canis familiaris"
 
def __init__(self, name):
self.name = name
 
rex = Dog("Rex")
bella = Dog("Bella")
 
print(rex.species, bella.species)
 
rex.species = "Wolf (just for Rex)"
print(rex.species, bella.species)
Output
Canis familiaris Canis familiaris
Wolf (just for Rex) Canis familiaris
1species is a class variable, shared by every Dog instance — both rex and bella see the same value.
2rex.species = "Wolf (just for Rex)" doesn’t change the shared class variable — it creates a brand new instance variable on rex specifically, which now shadows the class variable for that instance only.
3bella.species still reads the original class variable, since bella was never given its own instance variable of that name.
#use cases
Storing data that is genuinely the same across every instance, like a species name or a fixed configuration value
Counting how many instances of a class have been created, using a class variable incremented in __init__()
Sharing a default setting that individual instances can still override when needed
Understanding a common source of bugs, where an unintended assignment shadows a class variable instead of changing it

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.