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

Kabir Gandhiok
Kabir Gandhiok
12,553 Points

What is the advantage of using __add__?

Math can be done without using add like so:

from numstring import NumString

five = NumString(5) int(five) + 4 will give 9 or 4 + int(five) will also give 9

So what is the advantage of using add?

Thanks! Kabir

Steven Parker
Steven Parker
229,644 Points

Is this in reference to a particular video? A link to the video page (and a time index) might help clarify the question.

Kabir Gandhiok
Kabir Gandhiok
12,553 Points

@Steven, yeah this question is in reference to the controlling conversion video (first video in the Advanced Objects section)

Steven Parker
Steven Parker
229,644 Points

And which course is that section in? Could you provide a link to the video?

1 Answer

Steven Parker
Steven Parker
229,644 Points

Thanks for the video link, the issue is clear now.

So the value of defining "__add__" (and "__radd__/__iadd__") is so you don't need to do explicit conversions. As you pointed out, even without them you can do things like this:

int(five) + 4

But once you have defined the "magic" functions, you only need this:

five + 4

This can be very handy if your program will be performing a lot of math using the objects that have the math functions defined.

Kabir Gandhiok
Kabir Gandhiok
12,553 Points

Okay, I get it now.. Thanks for explaining that! :)