我先放代码:
Python 2.7.3 (default, Aug 1 2012, 05:16:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Item(object):
... def __init__(self, name, value={}):
... self.name = name
... self.value = value
... def __str__(self):
... return self.name + " - " + str(self.value)
... def addValues(self, value):
... for key,price in value.iteritems():
... self.value[key] = price
...
>>>
>>> item1 = Item('car')
>>> print item1
car - {}
>>> item2 = Item('truck')
>>> print item2
truck - {}
>>> item1.addValues({'blue':6000})
>>> print item1
car - {'blue': 6000}
>>> print item2
truck - {'blue': 6000}
>>>
我创建了 Item 类的两个实例,item1 和 item2。然后,我使用 addValues 方法更改了对象 item1 上字典属性的值。问题是,添加 item1 的字典属性,也为 item2 添加了相同的值。有人可以解释这里发生了什么吗?更改 item1 上的值如何更改 item2 上的值?我忽略了什么吗?