Python Tutorial

Understanding Class and Instance Variables in Python 3

Explains python class vs instance variables with examples, pitfalls (mutable class variables, shadowing), and best practices.

Drake Nguyen

Founder · System Architect

3 min read
Understanding Class and Instance Variables in Python 3
Understanding Class and Instance Variables in Python 3

Introduction

This guide compares python class vs instance variables and shows how to use them in object-oriented code. Class variables (also called class attributes) live on the class object and are shared across all instances. Instance variables (instance attributes) belong to each object and are typically created inside the constructor (__init__) using the self reference.

Prerequisites

You should have Python 3 installed and a basic understanding of classes and functions. Run examples in a REPL or save them to a .py file and execute with python3.

Class variables

Class variables python developers use when a value should be shared by every instance. Define them directly in the class body (outside any methods). They form part of the class namespace and are accessed through the class or via an instance.

class Shark:
    animal_type = "fish"   # class variable (python class attributes)

# Access through the class
print(Shark.animal_type)  # fish

# Access through an instance
s = Shark()
print(s.animal_type)      # fish

Shared state and modification

Because class variables are shared, changing them on the class affects all instances that don't override the attribute:

class Shark:
    followers = 5

# Modify at class level
Shark.followers = 10

a = Shark()
b = Shark()
print(a.followers, b.followers)  # 10 10

# Assigning on an instance creates/overrides an instance attribute (shadows class attribute)
a.followers = 3
print(a.followers, b.followers)  # 3 10

Mutable class variable pitfall

Using mutable objects (lists, dicts) as class variables can lead to unexpected behavior because the same object is shared across instances. Prefer instance attributes when each object needs its own mutable state.

class Team:
    members = []  # mutable class variable (shared!)

a = Team()
b = Team()
a.members.append('alice')
print(b.members)  # ['alice'] — unexpected sharing

# Safer: initialize in __init__ as an instance attribute
class SafeTeam:
    def __init__(self):
        self.members = []

Instance variables

Instance variables python programmers create in methods (typically __init__). These attributes are stored in each object’s instance namespace and can differ between instances.

class Shark:
    def __init__(self, name, age):
        self.name = name     # python instance attributes
        self.age = age

s1 = Shark('Sammy', 5)
s2 = Shark('Stevie', 8)
print(s1.name, s1.age)  # Sammy 5
print(s2.name, s2.age)  # Stevie 8

Attribute lookup order

When you access an attribute on an instance, Python looks first in the instance’s __dict__, then in the class and its base classes. This explains why an instance attribute can shadow a class attribute (python instance attribute shadows class attribute).

Class attributes vs instance attributes — a quick comparison

  • Scope: Class attributes are stored on the class; instance attributes on each object.
  • Sharing: Class variables python share across instances; instance variables are per object.
  • Initialization: Use class variables to set defaults shared by all instances; use __init__ to set per-instance data.
  • Mutability: Avoid mutable class variable defaults to prevent shared-state bugs (python class variable mutable default).
  • Shadowing: Assigning the same name on an instance creates/overrides the instance attribute.

Working with class and instance variables together

You often want both: class-level defaults combined with instance-specific values. Here’s a compact example demonstrating python class attribute vs instance attribute:

class Shark:
    species = 'Carcharodon'   # class attribute

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

s1 = Shark('Sammy')
s2 = Shark('Stevie')
print(s1.species, s1.name)  # Carcharodon Sammy
print(s2.species, s2.name)  # Carcharodon Stevie

Access and modification patterns

  • Read a class variable from an instance: instance.attr.
  • Change it for all instances: modify the class: Class.attr = value.
  • Change it for one instance: set an instance attribute with the same name (this shadows the class attribute).

Best practices and when to use each

  • Use class variables when a value is intrinsic to the class and should be shared (configuration, constants).
  • Use instance variables for per-object state, especially when using mutable types.
  • Prefer explicit initialization in __init__ to avoid python class variable mutable list pitfall.
  • Document when a class variable is intended to be modified at runtime (shared state) to avoid surprises.

Common gotchas

  • python access class variable from instance is allowed, but remember lookup order: instance → class → base classes.
  • python modify class variable from instance by assignment creates an instance attribute instead — to modify the class-level value, assign via the class.
  • Be careful with inheritance: subclasses inherit class variables and may shadow or override them.

Conclusion

Understanding python class attribute vs instance attribute helps you design clear, maintainable OOP code. Use class variables for shared, constant-like data and instance variables for object-specific state. Watch out for mutable class variables and attribute shadowing. With these patterns you can control shared state, follow DRY principles, and avoid common pitfalls in Python OOP.

Stay updated with Netalith

Get coding resources, product updates, and special offers directly in your inbox.