What is the difference between a class attribute and an instance attribute, and what does this code print?
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
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 9a.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__."