Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Stephen Cole
PLUS
Stephen Cole
Courses Plus Student 15,809 Points

Why doesn't __radd__ need to be explicitly coded? Is it because, by adding, it invokes the __add__ method?

I tested it and it works.

Kenneth says that we should do the "right thing" but I don't understand why the "right thing" works.

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points
  • If you have some_object + 4 then some_object.__add__() is called.
  • If you have 4 + some_object, then some_object.__radd__() is called

This is done because objects might behave differently depending on which side of the plus-sign they're on.

If symmetry exists, the having __radd__ call __add__ is a quick solution.

Chris Freeman
Chris Freeman
Treehouse Moderator 68,423 Points

Expanding answer:

There are two main choices,:

  • explicitly use the same code in __radd__ as is in __add__ (this is not DRY), or
  • call __add__ to have it do the work for __radd__.

So, yes, It is because __radd__ uses __add__.

Stephen Cole
PLUS
Stephen Cole
Courses Plus Student 15,809 Points

Right answer, wrong question.

I know/understand that __radd__ provides for reflective addition.

However, when overriding the __add__ method, I had to define how the addition worked. That is, if there was a period ('.') in the string, make it a float, otherwise, make it an int.

Why is it that I do not have to do the same thing with __radd__?

Is it because __radd__ uses __add__?

Is it because it assumes the type after it gets the first number?

Is there some other magic behind the scenes?

[MOD: added ` around build-in names to protect from formatting as bold]