Class Variable Vs Instance Variable Python

7 min read

Understanding the distinction between class variables and instance variables is a cornerstone of mastering object-oriented programming in Python. Worth adding: these two types of attributes define how data is stored, shared, and manipulated across objects, directly impacting memory usage, application logic, and the prevention of subtle bugs. While they may appear similar at first glance—both are defined inside a class body—their behavior diverges significantly the moment you instantiate objects and start assigning values.

The Fundamental Difference: Scope and Ownership

At the highest level, the difference comes down to ownership and lifecycle.

Instance variables are owned by individual objects (instances). Every time you create a new instance of a class, Python allocates fresh memory for that object’s instance variables. Changes made to an instance variable on one object never affect the same variable on another object. They are the primary mechanism for maintaining the unique state of an object—think of a User object having a unique username, email, or last_login timestamp.

Class variables, conversely, are owned by the class itself. They are shared across all instances of that class. There is only one copy of a class variable in memory, regardless of how many objects you instantiate. They are ideal for data that should be consistent across every object, such as configuration settings, default values, counters tracking the total number of instances created, or constants like PI or MAX_CONNECTIONS.

Defining Instance Variables: The __init__ Method

The standard and most Pythonic place to define instance variables is inside the __init__ method (the constructor). This ensures that every new object starts with its own initialized set of attributes.

class Dog:
    # Class variable (shared)
    species = "Canis familiaris"
    total_dogs = 0

    def __init__(self, name, age):
        # Instance variables (unique to each object)
        self.Here's the thing — name = name
        self. age = age
        Dog.

# Creating instances
dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 5)

print(dog1.name)        # Output: Buddy (Instance variable)
print(dog2.name)        # Output: Lucy  (Instance variable)
print(dog1.species)     # Output: Canis familiaris (Class variable accessed via instance)
print(Dog.

In this example, `name` and `age` belong strictly to `dog1` and `dog2`. `species` and `total_dogs` belong to the `Dog` class blueprint.

## The Namespace Lookup Chain: How Python Finds Attributes

To truly grasp the interaction between these two types, you must understand Python’s attribute lookup mechanism. When you write `obj.attribute`, Python follows a specific order:

1.  **Instance Dictionary (`obj.__dict__`)**: It checks the instance's own namespace first. If found, it returns the value immediately.
2.  **Class Dictionary (`obj.__class__.__dict__`)**: If not found in the instance, it looks at the class definition.
3.  **Parent Classes (MRO)**: If using inheritance, it traverses the Method Resolution Order up the inheritance chain.

This lookup chain creates a critical behavior: **Reading** a class variable via an instance works perfectly (`dog1.On the flip side, species` finds it in the class). That said, **Writing** (assignment) to that attribute via an instance *creates a new instance variable* that shadows the class variable. It does *not* modify the original class variable.

Honestly, this part trips people up more than it should.

## The Shadowing Trap: A Common Source of Bugs

This shadowing behavior is the number one source of confusion for developers transitioning from languages like Java or C++.

```python
class Counter:
    count = 0  # Class variable

c1 = Counter()
c2 = Counter()

print(c1.count)  # 0 (Reads class variable)
print(c2.count)  # 0 (Reads class variable)

c1.count += 1    # ATTEMPT TO MODIFY CLASS VARIABLE

print(c1.count)  # 0 (Still reads class variable)
print(Counter.In practice, count)  # 1 (Reads NEW instance variable 'count' on c1)
print(c2. count) # 0 (Class variable remains unchanged!

**What happened here?**
The expression `c1.count += 1` is syntactic sugar for `c1.count = c1.count + 1`.
1.  Python evaluates the right side: `c1.count` triggers a lookup. It finds `count` in the *class* (value 0).
2.  It adds 1 (result 1).
3.  It performs the assignment: `c1.count = 1`. Since assignment *always* writes to the instance namespace, Python creates a brand new `count` key in `c1.__dict__`.

Now `c1` has its own private `count` (value 1), shadowing the class `count` (value 0). `c2` and `Counter` still see the original class variable.

**How to correctly modify a class variable:**
You must reference the class explicitly: `Counter.count += 1`.

## The Mutable Class Variable Danger (The "Gotcha")

Shadowing is explicit assignment. A far more insidious bug occurs when a class variable holds a **mutable object** (like a `list`, `dict`, or `set`) and you *mutate* it in-place (using methods like `.Because of that, append()`, `. Because of that, update()`, `. extend()`) rather than reassigning it.

Because mutation does not trigger an assignment (`=`), Python does not create a new instance variable. It modifies the *single shared object* referenced by the class variable.

```python
class Team:
    # DANGER: Mutable default argument / class variable
    members = [] 

    def add_member(self, name):
        self.members.append(name) # Mutates the shared list!

t1 = Team()
t1.add_member("Alice")

t2 = Team()
t2.add_member("Bob")

print(t1.In real terms, members) # Output: ['Alice', 'Bob'] -> LEAKED DATA! print(t2.members) # Output: ['Alice', 'Bob']
print(Team.

Both `t1` and `t2` share the exact same list object in memory. That's why adding a member to one adds it to all. This is rarely the intended behavior for instance-specific data.

**The Fix:** Initialize mutable collections inside `__init__` as instance variables.

```python
class Team:
    def __init__(self):
        self.members = [] # New list for EVERY instance

    def add_member(self, name):
        self.members.append(name)

When to Use Which: Practical Guidelines

Choosing between class and instance variables is an architectural decision. Use this checklist to decide:

Use Instance Variables (self.attr) when:

  • Data is unique per object: Name, ID, email, current balance, position coordinates.
  • Data changes independently: One user logging out shouldn't log out all users.
  • Data involves mutable structures: Lists, dictionaries, or sets specific to that object's lifecycle.
  • You need encapsulation: The internal state of an object should be isolated.

Use Class Variables (ClassName.attr or attr inside class body) when:

  • Data is shared constants: PI = 3.14159, DEFAULT_TIMEOUT = 30, MAX_RETRIES = 3.
  • Tracking global state: instance_count = 0, active_connections = [] (if managed carefully).
  • Defining default values for configuration: default_page_size = 20. Instances can shadow this if they need a custom size (`self

default_page_size = 50` shadows the class default for that instance only).

  • Caching expensive computations: A result computed once and reused across all instances (a memoization cache).
  • Registry patterns: Keeping track of all subclasses, plugins, or available strategies.

A useful mental model: ask yourself "If I created a thousand of these objects, would this piece of data be copied a thousand times, or would it exist just once?" If the answer is "once," it belongs on the class Turns out it matters..

A Common Pattern: The Instance Counter

The classic example that ties everything together is tracking how many objects exist. Here the class variable is the shared counter, but note how we must reference the class explicitly to avoid shadowing:

class Widget:
    count = 0  # Shared across all instances

    def __init__(self, name):
        self.Worth adding: name = name          # Instance variable: unique per object
        Widget. count += 1         # Class variable: modifies the shared value
        self.id = Widget.

    def __repr__(self):
        return f"Widget(id={self.id}, name={self.name!r})"

a = Widget("first")
b = Widget("second")

print(a)            # Widget(id=1, name='first')
print(b)            # Widget(id=2, name='second')
print(Widget.count) # 2

Notice the interplay: count is genuinely shared and mutated through the class, while name and id are frozen per-instance snapshots. Getting this distinction right is what separates code that "happens to work" from code that behaves correctly under real usage.

Conclusion

Class variables and instance variables solve two fundamentally different problems. Instance variables describe what makes an object unique; class variables describe what all objects of a type have in common. Python's attribute lookup makes this convenient, but that same convenience hides a sharp edge: a plain self.attr = value silently creates an instance variable that shadows the class one, and in-place mutation of a shared mutable object leaks state across every instance.

The rules that keep you safe are simple to state and worth internalizing:

  • Reach for self.attr when the data belongs to one object.
  • Reach for ClassName.attr when the data belongs to the type as a whole.
  • Never store mutable collections as class variables if instances are meant to modify them, initialize them in __init__ instead.
  • When updating a shared class variable, always reference the class explicitly (ClassName.attr += 1), never self.

Master these distinctions and a whole category of subtle, hard-to-debug errors, shared mutable state, accidental shadowing, and cross-instance data leaks, simply disappears from your code.

Latest Batch

Coming in Hot

In That Vein

A Few Steps Further

Thank you for reading about Class Variable Vs Instance Variable Python. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home