我在看一本书,这里有这样一个例子(关于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中,这是好的。但是,从 "*args "开始 增加 方法,参数 "Other "接收第二个元组("Yellow"、"Purple"、"Cyan"),而这个元组是先在self.Input变量上。为了证明这一点,你可以在构造函数处使用print()语句和 增加 方法,而你则认为变量中的内容发生了变化。如果有任何Python程序员可以向我解释为什么会发生这种情况,我会很高兴。我很抱歉,如果它不是那么容易理解,因为英语不是我的第一语言。
再一次强调一下,例如:如果你把 "print (self.Input) "放在 启动 方法,你将能够看到它包含了两个元组(RGB和YPC),但是,如果你把 "print (self.Input) "放在 增加 方法,它将只打印RGB元组,而YPC元组将在 "Other.Input "处打印,我不知道是什么原因,基本上,这就是我的问题。为什么self.Input在构造方法里有两个元组,而在 "其他输入 "里却有两个元组?增加'方法,现在没有了?
通过添加一个 print
到代码中,你可以看到哪个实例是 self
并且是 other
当初 __add__
是执行。
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}")
prints:
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
),以及 self
是 value1
(其中包含 Red Green Blue
).
不确定你的问题到底是什么,但这是如何的 __add__
方法是有效的。每当你使用 +
运营商,它将调用 __add__
从左操作数传入,右操作数将作为参数传入。
所以当 Value1 + Value2
执行时,python。
__add__
方法从 Value1
和 Value1
被分配到 self
Value2
被传递到方法中,并被分配给 Other
参数。