最近学习了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 中可能吗?
__radd__
。此外,没有 __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__
你必须重载
__radd__
方法(右侧加法)。您的功能应该看起来与您的__add__
方法几乎相同,例如:
def __radd__(self, other):
return self.val + other.val