Problem Statement
Explain class variables versus instance variables and a common pitfall.
Explanation
A class variable is shared by all instances; an instance variable belongs to one object. Reading a missing instance attribute falls back to the class attribute via normal lookup.
A common pitfall is using a mutable class variable like a list and then mutating it through one instance, which affects all others. Prefer per-instance fields for mutable state by assigning in __init__.
Code Solution
SolutionRead Only
class Bag:
items=[] # shared
def __init__(self):
self.things=[] # per instance
b1=Bag(); b2=Bag()
b1.things.append(1)
Bag.items.append('X')