Welcome to the Treehouse Community
Looking to learn something new?
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 Parker216,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.