内置对象的重写运算符 [英] Override operator of built-in object
本文介绍了内置对象的重写运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想重写"dict"类的"+"运算符,以便能够轻松地合并两个字典.
I would like to override the "+" operator of the "dict" class, in order to be able to merge two dictionaries easily.
类似的东西:
def dict:
def __add__(self,other):
return dict(list(self.items())+list(other.items()))
通常可以重写内置类的运算符吗?
Is it possible in general to override the operator of a built-in class?
推荐答案
总之,没有:
>>> 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
子类化以添加运算符:
You need to subclass dict
to add the operator:
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)
就我个人而言,我不会打扰,只是拥有一个免费的功能即可.
Personally, I wouldn't bother and would just have a free function for doing that.
这篇关于内置对象的重写运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文