Difference Between Class and Instance Variables in Python

Use a class variable when every object should share one value, and an instance variable when each object needs its own. That rule is the difference between class and instance variables in Python: one lives on the class, the other on each object.

class Employee:
    company = "Summit Outdoor Co."   # class variable (shared)

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

Trouble starts when you assign to a class variable through an object, or store a list in one. Both bugs hide until a second object shows up.

In this tutorial, I’ll compare the two side by side on one small payroll class, then walk through shadowing, counters, shared lists and inheritance. Every result below came from a real run on Python 3.12.5.

Class Variables vs Instance Variables at a Glance

Here’s what the examples show:

FeatureClass variableInstance variable
DefinedIn the class body, outside methodsOn self, usually in __init__
CopiesOne, shared by every objectOne per object
Read throughEmployee.x or obj.xobj.x only
Assign via obj.x = ...Creates a shadowing instance copyChanges that object only
Change via Employee.x = ...Every object sees it (unless shadowed)Not possible
Mutable value (list)Shared by all objects – a common bugSafe, each object owns one
Typical useConstants, defaults, countersName, salary, per-object state

The sample is an Employee class at Summit Outdoor Co., a Denver retailer. Emily Carter earns $72,000.00 and Jacob Miller $65,500.00, and the company name and 3% raise rate are shared. If __init__ is new to you, start with the __init__ method in Python.

Where Class and Instance Variables Live in the Code

You create a class variable by assigning a name in the class body, and an instance variable by assigning it on self:

class Employee:
    company = "Summit Outdoor Co."   # class variable (shared)
    raise_rate = 0.03

    def __init__(self, name, salary):
        self.name = name             # instance variables
        self.salary = salary

    def salary_after_raise(self):
        return self.salary * (1 + self.raise_rate)


emily = Employee("Emily Carter", 72000.00)
jacob = Employee("Jacob Miller", 65500.00)

for person in (emily, jacob):
    print(f"{person.name:<13} {person.company}  "
          f"${person.salary_after_raise():,.2f}")

print("Through the class:", Employee.company, Employee.raise_rate)
try:
    print(Employee.name)
except AttributeError as err:
    print("AttributeError:", err)

Output:

Emily Carter  Summit Outdoor Co.  $74,160.00
Jacob Miller  Summit Outdoor Co.  $67,465.00
Through the class: Summit Outdoor Co. 0.03
AttributeError: type object 'Employee' has no attribute 'name'
VS Code output of a Python Employee class with class variables company and raise_rate and instance variables name and salary
Both employees read the same company and raise rate, but each keeps its own name and salary.

Emily’s raise works out to $74,160.00 and Jacob’s to $67,465.00. self.raise_rate finds the class value because the object has no attribute by that name.

Employee.name raises AttributeError, since name only exists on objects. How objects get built is covered in constructors in Python.

What Happens When You Change a Class Variable Through an Instance?

Same two employees. I’ll give Emily 5% through emily.raise_rate, then set the class value to 4%:

class Employee:
    raise_rate = 0.03

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary


emily = Employee("Emily Carter", 72000.00)
jacob = Employee("Jacob Miller", 65500.00)

emily.raise_rate = 0.05     # adds a NEW instance variable
print("emily:", emily.raise_rate, " jacob:", jacob.raise_rate,
      " class:", Employee.raise_rate)
print("emily.__dict__:", emily.__dict__)

Employee.raise_rate = 0.04  # changes the shared value
print("emily:", emily.raise_rate, " jacob:", jacob.raise_rate,
      " class:", Employee.raise_rate)

del emily.raise_rate        # drop the shadow
print("after del, emily:", emily.raise_rate)

Output:

emily: 0.05  jacob: 0.03  class: 0.03
emily.__dict__: {'name': 'Emily Carter', 'salary': 72000.0, 'raise_rate': 0.05}
emily: 0.05  jacob: 0.04  class: 0.04
after del, emily: 0.04
VS Code output showing a Python instance variable shadowing a class variable, with emily.__dict__ and the class value
Assigning through emily adds raise_rate to her __dict__, so the later class change skips her until the copy is deleted.

emily.raise_rate = 0.05 didn’t touch the class. It created an instance variable that hides, or shadows, the class one, so Jacob still reads 0.03.

After Employee.raise_rate = 0.04, Jacob gets 0.04 but Emily stays at 0.05. Python checks the object’s own __dict__ first, then the class. I dig into that dictionary in the Python __dict__ attribute guide.

Important: when you want to change a shared value, assign through the class name.

Why Doesn’t self.headcount += 1 Update the Class Counter?

Counting objects is the classic class-variable job. Same Employee class, now with three hires:

class Employee:
    headcount = 0

    def __init__(self, name):
        self.name = name
        self.headcount += 1      # bug: writes an instance copy


emily = Employee("Emily Carter")
jacob = Employee("Jacob Miller")
olivia = Employee("Olivia Brooks")

print("Employee.headcount:", Employee.headcount)
print("olivia.headcount:  ", olivia.headcount)
print("in olivia.__dict__:", "headcount" in olivia.__dict__)

Output:

Employee.headcount: 0
olivia.headcount:   1
in olivia.__dict__: True

The fix changes one line in __init__:

    def __init__(self, name):
        self.name = name
        Employee.headcount += 1  # fix: update the class itself

Output:

Employee.headcount: 3
olivia.headcount:   3
in olivia.__dict__: False
Before and after VS Code output: self.headcount += 1 leaves the Python class counter at 0, Employee.headcount += 1 counts 3
Left: self.headcount += 1 leaves the class at 0. Right: Employee.headcount += 1 counts all 3 hires.

self.headcount += 1 reads the class value 0, adds 1, then writes the result onto the object. Each employee gets its own headcount of 1, and the class stays at 0.

Employee.headcount += 1 updates the class, so all three objects read 3. A classmethod that does cls.headcount += 1 works the same way. For counters inside plain functions, see static variables in Python functions.

Mutable Class Variables: The Shared List Bug

Emily learns SQL and Jacob learns Excel, but you’ve put the skills list on the class:

class Employee:
    skills = []                    # bug: one shared list

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

    def add_skill(self, skill):
        self.skills.append(skill)


class FixedEmployee:
    def __init__(self, name):
        self.name = name
        self.skills = []           # fix: a new list per employee

    def add_skill(self, skill):
        self.skills.append(skill)


for cls in (Employee, FixedEmployee):
    emily, jacob = cls("Emily Carter"), cls("Jacob Miller")
    emily.add_skill("SQL")
    jacob.add_skill("Excel")
    print(f"{cls.__name__:<14} emily: {emily.skills}")
    print(f"{'':<14} jacob: {jacob.skills}")

Output:

Employee       emily: ['SQL', 'Excel']
               jacob: ['SQL', 'Excel']
FixedEmployee  emily: ['SQL']
               jacob: ['Excel']
VS Code output showing a Python list class variable shared by two objects, and the fix with a list created in __init__
With the list on the class, both employees show SQL and Excel. Creating the list in __init__ gives each one only their own skill.

append() doesn’t assign anything, so no instance copy is made. Both calls change the one list on the class.

Create mutable values in __init__ instead. It’s the same trap as a list default, covered in dataclass default values and type hints.

How Class Variables Work with Inheritance

Back to raise rates. Olivia Brooks is a manager earning $98,000.00, and managers get 5%. A subclass can redefine the class variable:

class Employee:
    raise_rate = 0.03

    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def salary_after_raise(self):
        return self.salary * (1 + self.raise_rate)


class Manager(Employee):
    raise_rate = 0.05              # managers only


emily = Employee("Emily Carter", 72000.00)
olivia = Manager("Olivia Brooks", 98000.00)
print(f"Emily:  ${emily.salary_after_raise():,.2f}")
print(f"Olivia: ${olivia.salary_after_raise():,.2f}")
print("Lookup order:", [c.__name__ for c in Manager.__mro__])

Output:

Emily:  $74,160.00
Olivia: $102,900.00
Lookup order: ['Manager', 'Employee', 'object']

Olivia’s raise is $102,900.00 and Emily’s stays at $74,160.00. Python looks the name up in the order Manager, Employee, object, and stops at the first match.

So you can change a default for one group without touching the parent. Passing data up to a parent is shown in calling a base class constructor with arguments.

When to Use a Class Variable Instead of an Instance Variable

  • Company-wide constants like a tax rate: class variable.
  • Defaults a subclass may override: class variable.
  • Counters of every object: class variable, updated through the class name.
  • Per-object data (name, salary) or any list you change: instance variable, set in __init__.

If a value should be shared but not changed from outside, the naming rules in private variables and data hiding in Python help.

Ask two things: do you need one copy or one per object, and are you assigning through the class or the object? Get those right and the bugs above go away.

Keep going with these object-oriented topics:

Frequently asked questions

Can I access a class variable through self?

Yes. self.x reads the class value when the object has no attribute named x. Assigning self.x = ... creates an instance copy instead.

How do I change a class variable for all objects?

Assign through the class: Employee.raise_rate = 0.04. Objects that already have their own copy keep it.

Is a class variable the same as a static variable?

It’s the closest thing Python has. It’s shared by every object, but it’s still a normal attribute on the class and can be shadowed.

Why do all my objects share the same list?

The list is a class variable. Create it in __init__ with self.items = [] so each object gets its own.

Can a class variable be accessed without creating an object?

Yes. Employee.company works without any instance. Instance variables need an object first.

Where are class and instance variables documented?

See Class and Instance Variables in the Python tutorial.