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
Kabir Gandhiok12,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?
Steven Parker228,991 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.