我无法理解这个关于重载运算符的例子

I can't understand this example about Overload Operators

我正在看书,这里有这个例子(关于 Python 中的重载运算符):

class MyClass:
   def __init__(self, *args):
      self.Input = args

   def __add__(self, Other):

      Output = MyClass()
      Output.Input = self.Input + Other.Input
      return Output

   def __str__(self):
      Output = ""
      for Item in self.Input:
         Output += Item
         Output += " "
      return Output

Value1 = MyClass("Red", "Green", "Blue")
Value2 = MyClass("Yellow", "Purple", "Cyan")
Value3 = Value1 + Value2

print("{0} + {1} = {2}"
      .format(Value1, Value2, Value3))

只是为了突出显示,这里是输出:

Red Green Blue  + Yellow Purple Cyan  = Red Green Blue Yellow Purple Cyan

所以,我知道这里发生了什么,但有一件事我不明白。 Value 1 和 Value 2 对象给“*args”两个元组,然后,代码把 "args" 放在 self.Input 中,就可以了。但是,从 add 方法开始,参数 "Other" 接收第二个元组 ("Yellow", "Purple", "Cyan") 和这个元组首先在 self.Input 变量上。为了证明这一点,您可以在构造函数中使用 print() 语句和 add 方法,并且变量中的内容发生了变化。如果有 Python 程序员可以向我解释为什么会这样,我将很高兴。如果它不是那么容易理解,我很抱歉,因为英语不是我的母语。

再次强调,例如:如果将 "print (self.Input)" 放在 init 方法中,您将能够看到它包含两个元组(RGB 和 YPC),但是,如果将 "print (self.Input)" 放在 add 方法中,它将仅打印 RGB 元组,而 YPC 元组将位于 "Other.Input",出于某种原因,我不知道,基本上,这就是我的问题:为什么 self.Input 在构造函数方法中有两个元组,但是在 'add' 方法,它不再存在了吗?

不确定您的问题到底是什么,但这就是 __add__ 方法的工作原理。
每当您使用 + 运算符时,它都会从左侧操作数调用 __add__
正确的操作数将作为参数传入。

所以当Value1 + Value2执行时,python:

  1. Value1 调用 __add__ 方法并且 Value1 被分配给 self
  2. Value2 被传递到方法并被分配给 Other 参数。

通过在代码中添加一个print,您可以在执行__add__时看到哪个实例是self,哪个实例是other

class MyClass:
    def __init__(self, *args: str):
        self.input = args

    def __add__(self, other: 'MyClass'):
        print(f"Adding {self} to {other}")
        return MyClass(*(self.input + other.input))

    def __str__(self) -> str:
        return " ".join(self.input)


value1 = MyClass("Red", "Green", "Blue")
value2 = MyClass("Yellow", "Purple", "Cyan")
value3 = value1 + value2

print(f"{value1} + {value2} = {value3}")

打印:

Adding Red Green Blue to Yellow Purple Cyan
Red Green Blue + Yellow Purple Cyan = Red Green Blue Yellow Purple Cyan

所以当你调用 value1 + value2 时,它与你调用 value1.__add__(value2) 是一样的。 other参数是value2(包含Yellow Purple Cyan),selfvalue1(包含Red Green Blue)。