gpt4 book ai didi

python - python中的运算符重载,对象位于运算符的右侧

转载 作者:太空狗 更新时间:2023-10-29 17:31:40 26 4
gpt4 key购买 nike

我最近学习了 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__ .另外,there are none对于 __le__()__ge__() 等,但正如 Joel Cornett 正确观察到的那样,如果您只定义 __lt__a > b 调用了 b__lt__ 函数,这提供了一种解决方法。

>>> 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__

关于python - python中的运算符重载,对象位于运算符的右侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10490610/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com