我正在读一本书,这里有这个示例(关于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'方法中不再有两个元组?
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 andthe right operand will be passed in as the argument.
So when
Value1 + Value2
is executed, python:__add__
method fromValue1
andValue1
gets assigned toself
Value2
gets passed in to the method and gets assigned toOther
parameter.By adding a
print
to the code you can see which instance isself
and which isother
at the time that__add__
is executed:印刷品:
So when you call
value1 + value2
, it's the same as if you saidvalue1.__add__(value2)
. Theother
argument isvalue2
(which containsYellow Purple Cyan
), andself
isvalue1
(which containsRed Green Blue
).