Python交换运算符覆盖

Bob*_*ano 10 python overriding operators symmetry

嗨,我想知道是否有办法在Python中进行对称运算符覆盖.例如,假设我有一个班级:

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

然后我可以这样做:

a = A(1)
a + 1
Run Code Online (Sandbox Code Playgroud)

但如果我尝试:

1 + a
Run Code Online (Sandbox Code Playgroud)

我收到一个错误.有没有办法覆盖运算符添加,以便1 + a可以工作?

Mos*_*oye 7

只需__radd__在您的班级中实施一种方法.一旦int类无法处理添加,__radd__if if实现就会接受它.

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

例如,要计算表达式x-y,其中y是具有__rsub__()方法的类的实例,y.__rsub__(x)如果x.__sub__(y)返回则调用NotImplemented.

同样适用于x + y.

另外,您可能希望您的类成为子类object.请参阅在Python中继承类"对象"的目的是什么?