Back to questionsWhy do both instances share one
MiddleDebuggingCommon
Why do both instances share one items list?
Each cart should have its own items, but adding to one shows up in the other.
class Cart:
items = []
def add(self, item):
self.items.append(item)
a = Cart(); b = Cart()
a.add("apple")
print(b.items) # ['apple'] -- leaked across instances!Find and fix the bug.
items = [] is a class attribute shared by every instance, so a and b mutate the same list and b.items shows ['apple']. Fix: initialize it per-instance in __init__: def __init__(self): self.items = [].
- Putting mutable state in a class attribute instead of
__init__ - Thinking
self.items.appendcreates a per-instance attribute - Believing
list()vs[]changes the sharing
- Why does reading
self.itemsfind the class attribute when no instance attribute exists? - When is a class attribute the right place for shared state?