17

我最近了解了 python 中的运算符重载,我想知道以下是否可能。

考虑以下假设/人为类。

class My_Num(object):
    def __init__(self, val):
        self.val = val
    def __add__(self, other_num):
        if isinstance(other_num, My_Num):
            return self.val + other_num.val
        else:
            return self.val + other_num

我知道上面写的方式,我可以做这样的事情

n1 = My_Num(1)
n2 = My_Num(2)
n3 = 3
print n1 + n2
print n1 + n3

这些将按预期工作。我也知道它目前的写法我不能这样做

n1 = My_Num(1)
n2 = 2
print 2 + n1

有没有办法解决?我知道这个例子是人为的,但是我有一个应用程序,如果在我进行运算符重载时,我定义运算符的类可以出现在运算符的右侧,它将非常有用。这在python中可能吗?

4

2 回答 2

14

是的。例如,有__radd__. 此外,没有for __le__()__ge__()等,但正如 Joel Cornett 正确观察到的那样,如果您仅定义__lt__,则a > b调用 的__lt__函数b,这提供了一种解决方法。

>>> class My_Num(object):
...     def __init__(self, val):
...         self.val = val
...     def __radd__(self, other_num):
...         if isinstance(other_num, My_Num):
...             return self.val + other_num.val
...         else:
...             return self.val + other_num
... 
>>> n1 = My_Num(1)
>>> n2 = 3
>>> 
>>> print n2 + n1
4
>>> print n1 + n2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'My_Num' and 'int'

请注意,至少在某些情况下,这样做是合理的:

>>> class My_Num(object):
...     def __init__(self, val):
...         self.val = val
...     def __add__(self, other_num):
...         if isinstance(other_num, My_Num):
...             return self.val + other_num.val
...         else:
...             return self.val + other_num
...     __radd__ = __add__
于 2012-05-07T23:46:35.530 回答
2

您必须重载该__radd__方法(右侧添加)。您的函数应该看起来与您的方法几乎相同__add__,例如:

def __radd__(self, other):
     return self.val + other.val
于 2012-05-07T23:50:38.840 回答