smi*_*453 4 python overloading class add operator-keyword
我正在尝试添加一个带有数字的类对象,但我对如何添加带有两个数字的类对象感到困惑.例如,这是我假设的添加类方法:
class A:
def __add__(self, b):
return something
Run Code Online (Sandbox Code Playgroud)
我知道如何添加到目前为止:
object = A()
print(object + 1)
Run Code Online (Sandbox Code Playgroud)
但是,如果我想像这样添加它怎么办?
object = A()
print(object + 1 + 2)
Run Code Online (Sandbox Code Playgroud)
我应该使用*args作为add class方法吗?
Mar*_*ers 10
不,你不能使用多个参数.Python分别执行每个+运算符,这两个+运算符是不同的表达式.
对你的例子来说,object + 1 + 2确实如此(object + 1) + 2.如果(object + 1)生成一个具有__add__方法的对象,那么Python将为第二个运算符调用该方法.
例如,您可以返回A此处的另一个实例:
>>> class A:
... def __init__(self, val):
... self.val = val
... def __repr__(self):
... return f'<A({self.val})>'
... def __add__(self, other):
... print(f'Summing {self} + {other}')
... return A(self.val + other)
...
>>> A(42) + 10
Summing A(42) + 10
<A(52)>
>>> A(42) + 10 + 100
Summing A(42) + 10
Summing A(52) + 100
<A(152)>
Run Code Online (Sandbox Code Playgroud)
您希望返回值本身是一个对象,它也支持添加操作,例如:
class A:
def __init__(self, value=0):
self.value = value
def __add__(self, b):
return A(self.value + b)
def __str__(self):
return str(self.value)
a = A()
print(a + 1 + 2)
Run Code Online (Sandbox Code Playgroud)
输出:
3