Operator overloading

A forum for general discussion of the Python programming language.

Operator overloading

Postby ooleyguy » Tue Apr 16, 2013 5:31 am

I'm reading a book I got at the library about Python 3 (Introduction to Programming Using Python) and have understood it all so far and done all the exercises, but I've gotten to the part on operator overloading.

I see how it is done based on the examples, but no where does it tell me why it's done. Why use

Code: Select all
print("s1 + s2 is", s1.__add__(s2))


when

Code: Select all
print("s1 + s2 is", s1 + s2)


works and is easier for anyone lucky enough to read my code to understand?
ooleyguy
 
Posts: 6
Joined: Thu Apr 04, 2013 7:47 pm

Re: Operator overloading

Postby setrofim » Tue Apr 16, 2013 5:52 am

ooleyguy wrote: Why use

Code: Select all
print("s1 + s2 is", s1.__add__(s2))


when

Code: Select all
print("s1 + s2 is", s1 + s2)


works and is easier for anyone lucky enough to read my code to understand?

There is absolutely no good reason. You should never call the double underscore methods like that and should always use the corresponding operator instead. I believe your book is just trying to illustrate that the effect is the same (when you say "s1 + s2", the __add__ method of s1 gets invoked under the hood). The point of methods like __add__ is that you can override them in you classes' implemntations to all you to use normal Python operators (like +) on your custom classes. (Note: there are some situations where you would access some double underscore attributes, though not __add__, directly; but they are somewhat advanced, so don't worry about that for now).
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: Operator overloading

Postby ooleyguy » Tue Apr 16, 2013 7:42 pm

Thank you.
ooleyguy
 
Posts: 6
Joined: Thu Apr 04, 2013 7:47 pm


Return to General Discussions

Who is online

Users browsing this forum: Bing [Bot] and 3 guests