我想覆盖“dict”类的“+”运算符,以便能够轻松合并两个字典。
像这样的东西:
def dict:
def __add__(self,other):
return dict(list(self.items())+list(other.items()))
通常是否可以覆盖内置类的运算符?
我想覆盖“dict”类的“+”运算符,以便能够轻松合并两个字典。
像这样的东西:
def dict:
def __add__(self,other):
return dict(list(self.items())+list(other.items()))
通常是否可以覆盖内置类的运算符?
一句话,不:
>>> 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)
就个人而言,我不会打扰,只会有一个免费的功能来做到这一点。
您可以创建 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'
这可能如下所示:
class MyDict(dict):
def __add__(self,other):
return MyDict(list(self.items())+list(other.items()))