4 ms·
A slightly more realistic example: class Bag(object): def __init__(self, items=[]): self.items = items def add_item(self, item
by ajanuary 12y ago
A slightly more realistic example:
class Bag(object):
def __init__(self, items=[]):
self.items = items
def add_item(self, item):
# check the item is valid
self.items.append(item)
bag1 = Bag()
bag1.add('an item')
bag2 = Bag()
print(bag2.items)
- mark-r 12y agoAgain, the problem is not what it appears. You're keeping a reference to an existing item rather than making a copy. The results would be just as bad if you passed in an initial list rather than taking the default. initial = ['first item'] bag3 = Bag(initial) bag3.add_item('second item') print(initial) I think the surprising thing to most people is that you don't automatically get a copy when you do the assignment. That's how it works in older languages like C and C++, and how it appears to behave when you use immutable objects.