mar*_*ega 13 python operator-overloading
我最近在python中了解了运算符重载,我想知道以下是否可行.
考虑下面的hypothetica /设法类.
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
Run Code Online (Sandbox Code Playgroud)
我知道上面写的方式,我可以做这样的事情
n1 = My_Num(1)
n2 = My_Num(2)
n3 = 3
print n1 + n2
print n1 + n3
Run Code Online (Sandbox Code Playgroud)
这些将按预期工作.我也知道它目前写的方式我不能这样做
n1 = My_Num(1)
n2 = 2
print 2 + n1
Run Code Online (Sandbox Code Playgroud)
有没有办法解决?我知道这个例子是设计的,但是我有一个应用程序,如果我在运算符重载时,它将非常有用,我定义运算符的类可以出现在运算符的右侧.这在python中可能吗?
sen*_*rle 12
是.例如,有__radd__.另外,有没有对__le__(),__ge__()等等,但是乔尔科内特正确地指出,如果只定义__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'
Run Code Online (Sandbox Code Playgroud)
请注意,至少在某些情况下,执行以下操作是合理的:
>>> 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__
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3980 次 |
| 最近记录: |