How does operator overload work?

Asked

Viewed 160 times

2

How this code works?

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))





  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

3

It’s not very secret, the operator used in an expression is actually a syntactic sugar, so it’s not quite what you’re seeing. In fact the line

Value3 = Value1 + Value2

It will perform something like

Value3 = Value1.__add__(Value2)

So it’s just called the method described in the class.

Note that the first operand will determine which class will be used to call the method, since this method may be present in several classes. In the case Value1 is the type MyClass so it’s the method __add__() inside MyClass which will be called, but this is not even about the operator, applies to any method.

It is a little different because the Operator has special features in the language, mainly it can be noticed precedence between operators when there are several operands and need to decide which operator is executed first, if it were a normal method there will be no precedence, only association.

  • Yeah, I got that part, thanks. But for example, can you explain to me how variables like "Output.Input" or "Other.Input" work, and why they are linked like this? For example, in the way add, it has an argument 'Other', but soon after, when it defines 'Output.Input', 'Other' is appended with a point '.' the word 'Input', this I did not understand, this appending from a point, since 'Other' is an existing argument and it receives the values of "Value 2" (at the end of the code)

  • 2

    That’s not the overload, that’s a specific algorithm, that’s another question. Anyway, it sounds like you’re doing more sophisticated than you realize. To give you an example, you asked a question about how to paint a house, when you still don’t know how to lay a brick, you are learning the wrong way and creating confusion. Look for a more structured way to learn by taking each concept at a time in an order established by someone who knows what is most important first. This concept predates the overload. When you ask an advanced question you are presumed to know the basics

  • Thanks, I got to understand agr.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.