我正在尝试将项目附加到实例化对象的列表中:
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']
我期望的行为是灯泡在living_room.contents中,而不是在dining_room.contents中。谁能解释一下呢?
答案 0 :(得分:2)
contents
是一个可变的默认参数。它的默认值(空列表)仅创建一次,而不是每次调用。
以下是更多详情: http://docs.python-guide.org/en/latest/writing/gotchas/