附加到实例化对象中的列表

时间:2016-05-07 20:55:06

标签: python oop

我正在尝试将项目附加到实例化对象的列表中:

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中。谁能解释一下呢?

1 个答案:

答案 0 :(得分:2)

contents是一个可变的默认参数。它的默认值(空列表)仅创建一次,而不是每次调用。

以下是更多详情: http://docs.python-guide.org/en/latest/writing/gotchas/