我想重写"dict“类的"+”操作符,以便能够轻松地合并两个字典。
就像这样:
def dict:
def __add__(self,other):
return dict(list(self.items())+list(other.items()))一般情况下,可以覆盖内置类的操作符吗?
发布于 2013-10-16 13:29:22
总之,不:
>>> dict.__add__ = lambda x, y: None
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'dict'您需要子类dict来添加操作符:
import copy
class Dict(dict):
def __add__(self, other):
ret = copy.copy(self)
ret.update(other)
return ret
d1 = Dict({1: 2, 3: 4})
d2 = Dict({3: 10, 4: 20})
print(d1 + d2)就我个人而言,我不会麻烦,我只会有一个免费的功能来做。
发布于 2013-10-16 13:31:34
这可能如下所示:
class MyDict(dict):
def __add__(self,other):
return MyDict(list(self.items())+list(other.items()))https://stackoverflow.com/questions/19404796
复制相似问题