【发布时间】:2015-04-29 00:49:58
【问题描述】:
我有一个 K() 类,它有一个 __add__() 方法,其工作原理如下
d_1 = K(dict(a=3, b=5), dict(b=45,c=23))
d_2 = K(dict(a='three',b='two'), dict(b='wa',c='wo'))
>>d = d_1 + d_2
>>d == K({'a': 3, 'b': 5}, {'b': 45, 'c': 23}, {'a': 'three', 'b': 'two'}, {'b': 'wa', 'c': 'wo'})
True
但是,如果我更改一些数据
d_1['c'] = 'apples'
d_2['c'] = 'oranges'
然后再次检查...
>>d == K({'a': 3, 'b': 5}, {'b': 45, 'c': 23}, {'a': 'three', 'b': 'two'}, {'b': 'wa', 'c': 'wo'})
False
变化的数据影响了原来的添加方式。我尝试使用 .copy() 来创建我们正在添加的变量的副本,并使用它们 - 但是我没有任何运气......
def __add__(self, other):
scopy, ocopy = self.copy(),other.copy()
slist,olist = [],[]
for x in scopy.list_of_dictionaries_from_init:
self_temp.append(x)
for i in other_copy.list_of_dictionaries_from_init:
temp.append(i)
return K(*(self_copy.list_of_dictionaries_from_init + olist))
这完全行不通
我不确定如何使用副本进行这项工作
【问题讨论】:
标签: python dictionary operator-overloading