← Back

Home β€Ί Problems β€Ί Class variable shared across instances

Class variable shared across instances

🧠 Predict the output Topic: oop Difficulty: medium Free

What this problem practises

Object-oriented bugs hide in state: class attributes shared by every instance, mutable defaults declared in __init__ signatures, and methods that mutate self when the caller expected a copy.

This is an output-prediction problem: read the snippet carefully and write down exactly what it prints before anything runs. These questions are interview staples because they test whether you know the language rules, or merely recognise their syntax.

Difficulty: medium β€” expect to hold two interacting rules in your head at once, such as a boundary combined with a mutation.

The challenge

The code runs in PyDebug’s in-browser compiler. Open the problem, run the snippet, watch the exact error or output, and keep iterating until it is right. Signed-in solves count toward XP and your daily streak.

The snippet

The interactive editor pre-fills exactly this code β€” read it, then submit your prediction:

class Counter:
    count = 0
    def increment(self):
        Counter.count += 1

a = Counter()
b = Counter()
a.increment()
b.increment()
print(a.count)
print(b.count)

Understand the rule

An attribute assigned in the class body belongs to the class itself, and every instance reads it through lookup β€” so a mutable class attribute like a list is shared: dog1.tricks.append('sit') shows up in dog2.tricks. Assignment through an instance, in contrast, creates a new instance attribute that shadows the class one. Distinguishing read-through from write-shadowing is the whole puzzle.

How to trace it

  1. Classify each attribute: defined in the class body (class attribute) or via self.x = ... in __init__ (instance attribute).
  2. Reads fall through: instance first, then class β€” two fresh instances read the same class attribute.
  3. Mutations (append, update) on a class attribute act on the one shared object; all instances observe them.
  4. Assignments (self.x = ...) create an instance attribute that shadows the class one for that instance only.

Common wrong fixes

Rule to remember

Class attributes are shared; instance assignment shadows them. Mutating a shared object affects every instance β€” per-instance state belongs in __init__.

Solve it in the interactive editor β†’

πŸ’Ό Learning path: Interview Practice

Problem 2 of 16 in this path. Work them in order β€” each one builds on the rule before it.

← Mutable default argument trapNext in path: List copy vs reference β†’

More oop problems

Keep going