Interview Q&A / Python

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What is the difference between a class attribute and an instance attribute, and what does this code print?

SHORT ANSWER

A class attribute is shared by all instances. An instance attribute belongs to one object. Assigning through an instance, like a.count = 5, creates a new instance attribute that shadows the class one, but mutating a shared list changes it for everyone.

Explain it simply

A class attribute is a notice on the common hostel board that every student can read. An instance attribute is something pinned inside one student's own room. If you write "count = 5" on your own door, the board is untouched, but your room now answers with 5. If instead you scribble on a shared list hanging from the board, everyone sees the change.

Example

python
class Counter:
    total = 0
    tags = []

a = Counter()
b = Counter()

a.total = 5
print(a.total, b.total, Counter.total)   # Output: 5 0 0

a.tags.append("x")
print(b.tags)                            # Output: ['x']

Counter.total = 9
print(a.total, b.total)                  # Output: 5 9

a.total = 5 only creates an instance attribute on a. Later, Counter.total = 9 changes the class value, which b still reads, while a keeps its own 5. The list is the same object for every instance, so a mutation through a shows up in b.

What to say in the interview

"Class attributes live on the class and are shared; instance attributes live on each object. Reading checks the instance first, then the class. Assignment through an instance always creates an instance attribute. Mutable class attributes like lists are shared, so I initialise per-object data in __init__."

#python#oop#output-puzzles

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.