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

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
216,136 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
216,136 Points

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

1 Answer

Steven Parker
Steven Parker
216,136 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! :)