How does operator overload work?
How does this code work?
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))
1 answers
Doesn't have much secret, the operator used in an expression is actually a syntactic sugar, so it's not quite what you're seeing. Actually the line
Value3 = Value1 + Value2
Will execute something like
Value3 = Value1.__add__(Value2)
Then only the method described in the class is called.
Note that the first operand will determine which class will be used to call the method, since this method can be present in several classes. In the case Value1
is of type MyClass
so it is the method __add__()
within MyClass
that will be called, but this is not even about the operator, it goes for any method.
It is a little different because the operator has special features in the language, mainly can be noticed precedence between operators when there are several operands and need to decide which operator is executed first, if it was a normal method there will be no precedence, only Association.