Python 交换运算符覆盖

Python commutative operator override

您好,我想知道是否有一种方法可以在 Python 中进行对称运算符覆盖。例如,假设我有一个 class:

class A:
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        if isinstance(other, self.__class__):
            return self.value + other.value
        else:
            return self.value + other

那我可以这样做:

a = A(1)
a + 1

但如果我尝试:

1 + a

我收到一个错误。 有没有办法覆盖运算符 add 以便 1 + a 起作用?

只需在 class 中实现一个 __radd__ 方法。一旦 int class 无法处理加法,__radd__ 如果实现了,就会接受它。

class A(object):
    def __init__(self, value):
        self.value = value

    def __add__(self, other):
        if isinstance(other, self.__class__):
            return self.value + other.value
        else:
            return self.value + other

    def __radd__(self, other):
        return self.__add__(other)


a = A(1)
print a + 1
# 2
print 1 + a
# 2

For instance, to evaluate the expression x - y, where y is an instance of a class that has an __rsub__() method, y.__rsub__(x) is called if x.__sub__(y) returns NotImplemented.

同样适用于 x + y

附带说明一下,您可能希望 class 低于 class object。参见 What is the purpose of subclassing the class "object" in Python?