覆盖内置对象的运算符

Oli*_*Oli 3 python operator-overloading

我想覆盖"dict"类的"+"运算符,以便能够轻松地合并两个字典.

像这样的东西:

def dict:
  def __add__(self,other):
    return dict(list(self.items())+list(other.items()))
Run Code Online (Sandbox Code Playgroud)

通常可以覆盖内置类的运算符吗?

NPE*_*NPE 7

总之,没有:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

您需要子类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)
Run Code Online (Sandbox Code Playgroud)

就个人而言,我不会打扰,只会有一个免费的功能.