Python 运算符重载多个操作数

Python operator overloading with multiple operands

我知道我可以通过以下方式在 python 中进行简单的运算符重载。

假设重载“+”运算符。

class A(object):
  def __init__(self,value):
    self.value = value

  def __add__(self,other):
    return self.value + other.value

a1 = A(10)
a2 = A(20)
print a1 + a2

但是当我尝试执行以下操作时它失败了,

a1 = A(10)
a2 = A(20)
a3 = A(30)
print a1 + a2 + a3

因为 __add__ 只接受 2 个参数。用 n 个操作数实现运算符重载的最佳解决方案是什么。

这是失败的,因为 a1 + a2 return 一个 int 实例及其 __add__ 被调用,它不支持自定义 class A;您可以 return __add__ 中的 A 实例来消除此特定操作的异常:

class A(object):
  def __init__(self,value):
    self.value = value

  def __add__(self,other):
    return type(self)(self.value + other.value)

将它们加在一起现在可以按预期方式运行:

>>> a1 = A(10)
>>> a2 = A(20)
>>> a3 = A(30)
>>> print(a1 + a2 + a3)
<__main__.A object at 0x7f2acd7d25c0>
>>> print((a1 + a2 + a3).value)
60

这个class当然会遇到与其他操作相同的问题;您需要将其他 dunders 实施到 return 您的 class 的实例,否则您会遇到与其他操作相同的结果。

如果你想在 print 这些对象时显示一个好的结果,你还应该实现 __str__ 到 return 调用时的值:

class A(object):
    def __init__(self,value):
        self.value = value

    def __add__(self,other):
        return A(self.value + other.value)

    def __str__(self):
        return "{}".format(self.value)

现在打印出你需要的效果了:

>>> print(a1 + a2 + a3)
60

问题在于

a1 + a2 + a330 + a3

30 是一个整数,整数不知道如何求和到 A

您应该 return 在您的 __add__ 函数中创建一个 A 的实例