T. Arboreus T. Arboreus - 2 years ago 102
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) # []


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 Source

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/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download