首页 > 解决方案 > 我可以更改 Python 中的默认 __add__ 方法吗?

问题描述

是否可以更改默认__add__方法以执行其他操作而不只是添加?

例如,如果目标是这一行: 5+5getThe answer is 10或其他类似的东西,0通过更改__add__为 bex-y而不是x+y?

我知道我可以改变__add__自己的课程:

class Vec():
    def __init__(self,x,y):
        self.x = x
        self.y = y
    
    def __repr__(self):
        return f'{self.x, self.y}'

    def __add__(self, other):
        self.x += other.x
        self.y += other.y
        return Vec(self.x,self.y)

    
v1 = Vec(1,2)
v2 = Vec(5,3)

v1+v2
# (6, 5)

我可以以某种方式定位默认__add__方法来改变其行为吗?我直观地认为__add__在每个默认数据类型中定义了返回特定结果,但话说回来,该__add__方法是我们为特定类更改它时要解决的问题,那么,是否可以更改主要__add__逻辑?

这些方面的东西?

class __add__():
    ...

标签: pythonmagic-methods

解决方案


是的,您可以重载用户定义的类中的任何内容。

class Vec():
    def __init__(self,x,y):
        self.x = x
        self.y = y
    
    def __repr__(self):
        return f'{self.x, self.y}'

    def __add__(self, other):
        self.x += other.x
        self.y += other.y
        return Vec(self.x,self.y)

    
v1 = Vec(1,2)
v2 = Vec(5,3)

print(v1+v2)

# using lambda function
Vec.__add__ = lambda self,other: Vec(self.x-other.x,self.y-other.y)
print(v1+v2)

# using "normal" function
def add(self,other):
    self.x -= other.x
    self.y -= other.y
    return Vec(self.x,self.y)
Vec.__add__ = add
print(v1+v2)

不适用于内置类型,例如导致TypeError: can't set attributes of built-in/extension type 'set'

另请注意,您的实现__add__修改了我不喜欢的原始实例..(只是我的注释)


推荐阅读