当我发现一些东西时,我正在尝试在 python 中使用 dunders:假设我创建了一个类:
class MyInt:
def __init__(self, val):
self.val = val
def __add__(self, other):
return self.val + other
a = MyInt(3)
Run Code Online (Sandbox Code Playgroud)
该__add__工程时,这是运行完美的罚款:
>>> print(a + 4)
7
Run Code Online (Sandbox Code Playgroud)
但是,当我运行此命令时:
>>> print(4 + a)
TypeError: unsupported operand type(s) for +: 'int' and 'MyInt'
Run Code Online (Sandbox Code Playgroud)
我知道该int课程不支持添加 with MyInt,但是有什么解决方法吗?
Gre*_*Guy 10
这就是该__radd__方法的用途 - 如果您的自定义对象位于运算符的右侧,而运算符的左侧无法处理它。请注意,如果可能,运算符的左侧将优先。
>>> class MyInt:
... def __init__(self, val):
... self.val = val
... def __add__(self, other):
... return self.val + other
... def __radd__(self, other):
... return self + other
...
>>> a = MyInt(3)
>>> print(a + 4)
7
>>> print(4 + a)
7
Run Code Online (Sandbox Code Playgroud)
对于任何给定的运算符,您可以覆盖的第三个“隐藏”方法是__iadd__,它对应于赋值运算符+=。