在Python中使用带有多个参数的__add__运算符 [英] Using __add__ operator with multiple arguments in Python
问题描述
我试图添加带有数字的类对象,但是我对如何添加带有两个数字的类对象感到困惑.例如,这是我假设的 add 类方法:
I am trying to add a class object with a number, but I'm confused on how to go about adding a class object with two numbers. For example, this is my hypothetical add class method:
class A:
def __add__(self, b):
return something
到目前为止,我知道如何添加此内容:
I know how to add this so far:
object = A()
print(object + 1)
但是,如果我想这样添加它怎么办?
But, what if I want to add it like this?
object = A()
print(object + 1 + 2)
我应该将* args用于 add 类方法吗?
Should I use *args for the add class method?
推荐答案
不,您不能使用多个参数. Python分别执行每个+
运算符,这两个+
运算符是不同的表达式.
No, you can't use multiple arguments. Python executes each +
operator separately, the two +
operators are distinct expressions.
在您的示例中,object + 1 + 2
确实是(object + 1) + 2
.如果(object + 1)
生成的对象具有__add__
方法,则Python将为第二个运算符调用该方法.
For your example, object + 1 + 2
really is (object + 1) + 2
. If (object + 1)
produces an object that has an __add__
method, then Python will call that method for the second operator.
例如,您可以在此处返回A
的另一个实例:
You could, for example, return another instance of A
here:
>>> 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)>
这篇关于在Python中使用带有多个参数的__add__运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!