我无法理解有关重载运算符的此示例

我正在读一本书,这里有这个示例(关于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

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

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

评论
wsed
wsed

Not sure what your question is exactly, but that's how __add__ method works.
Whenever you use + operator, it'll call __add__ from the left operand and
the right operand will be passed in as the argument.

So when Value1 + Value2 is executed, python:

  1. calls __add__ method from Value1 and Value1 gets assigned to self
  2. Value2 gets passed in to the method and gets assigned to Other parameter.
点赞
评论
cut
cut

By adding a print to the code you can see which instance is self and which is other at the time that __add__ is executed:

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

So when you call value1 + value2, it's the same as if you said value1.__add__(value2). The other argument is value2 (which contains Yellow Purple Cyan), and self is value1 (which contains Red Green Blue).

点赞
评论