T. Arboreus T. Arboreus - 6 months ago 21
Python Question

Appending to a list in an instantiated object

I'm trying to append items to a list in an instantiated object:

class Room(object):
def __init__(self, name, contents=[]):
self.name = name
self.contents = contents


living_room = Room('living room')
dining_room = Room('dining room')

print(living_room.contents) # []
print(dining_room.contents) # []

living_room.contents.append('lamp')

print(living_room.contents) # ['lamp']
print(dining_room.contents) # ['lamp']


The behavior I would expect would be for the lamp to be in living_room.contents, but not in dining_room.contents. Can anyone explain this?

jab jab
Answer

contents is a mutable default argument. It's default value (the empty list) is only created once, not for every call.

Here are more details: http://docs.python-guide.org/en/latest/writing/gotchas/

Comments