Python commutative operator override

南笙酒味 提交于 2019-11-30 02:47:22

问题


Hi I was wondering if there is a way to do a symmetric operator override in Python. For example, let's say I have a 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

Then I can do:

a = A(1)
a + 1

But if I try:

1 + a

I get an error. Is there a way to override the operator add so that 1 + a will work?


回答1:


Just implement an __radd__ method in your class. Once the int class can't handle the addition, the __radd__ if implemented, takes it up.

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.

Same applies to x + y.

On a side note, you probably want your class to subclass object. See What is the purpose of subclassing the class "object" in Python?



来源:https://stackoverflow.com/questions/42071861/python-commutative-operator-override

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!