Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

Stephen Cole
PLUS
Stephen Cole
Courses Plus Student 15,592 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,154 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,154 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,592 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]