我想覆盖" +" " dict"的运营商class,以便能够轻松地合并两个词典。
类似的东西:
def dict:
def __add__(self,other):
return dict(list(self.items())+list(other.items()))
通常可以覆盖内置类的运算符吗?
答案 0 :(得分:6)
总之,不,
>>> 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)
就个人而言,我不会打扰,只会有自由功能。
答案 1 :(得分:3)
你可以创建dict的子类(如@NPE所说):
class sdict(dict):
def __add__(self,other):
return sdict(list(self.items())+list(other.items()))
site.py
为什么不创建您自己的 Python Shell ?
以下是一个例子:
#!/usr/bin/env python
import sys
import os
#Define some variables you may need
RED = "\033[31m"
STD = "\033[0m"
class sdict(dict):
def __add__(self,other):
return dict(list(self.items())+list(other.items()))
dict = sdict
sys.ps1 = RED + ">>> " + STD
del sdict # We don't need it here!
# OK. Now run our python shell!
print sys.version
print 'Type "help", "copyright", "credits" or "license" for more information.'
os.environ['PYTHONINSPECT'] = 'True'
答案 2 :(得分:1)
这可能如下所示:
class MyDict(dict):
def __add__(self,other):
return MyDict(list(self.items())+list(other.items()))