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

waleed aljarman
waleed aljarman
1,657 Points

Do Magic Methods run according to order?

https://teamtreehouse.com/library/math

In defining the radd and iadd, he didn't use int(self), is it because it's already an int from before?

1 Answer

Josh Keenan
Josh Keenan
19,652 Points

No, they are ran when called. So the __add__ is actually the same as my_object.add() they aren't ran when defined, just defined. With regards to __radd__, it is right side add.

length = Length(5, "m") + 5          # our imaginary class is Length, and taking that and adding 5 to it
length = 5 + Length (5, "m") .       # now we try taking 5 and adding a length to it

The first line here works fine, because we are also going to assume we have defined our __add__ for the class. It knows it is just adding 5 to the class value.

The second line however tries to add our class Length to the integer 5, and the integer 5 is calling the int.__add__ method when it is adding the two, and it doesn't know how to handle adding our new class to an integer. This is where __radd__ comes in, it tries to do int.__add__ and if that doesn't work it tries to use Length.__radd__ which we will say looks like this:

    def __radd__(self, other):
        return Length.__add__(self,other)  

Now the interpreter will run Length.__radd__ and add the two. Hope this makes sense and feel free to ask any questions