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 trialSon-Hai Nguyen
2,481 PointsWhat if I say ```return self + other``` in add method?
What if I say like this for the add method?
def __add__(self, other):
return self + other
I tried to run it and python gave me an error RecursionError: maximum recursion depth exceeded while calling a Python object
but I dont know what that is and I dont know why.
Thanks guys!!!
1 Answer
Steven Parker
231,248 PointsWhen you refer to "self" directly, you're asking the system to perform an operation implicitly using the "__add__
" method of the class, which is what you are defining here. And when a method calls itself, this is called "recursion".
Since each time the method starts, it causes the system to call itself again, this creates a loop that never ends. Eventually (but not long in human time) the system reaches an internal limit and gives you that error.
So it's necessary to perform the conversion explicitly before the math is performed. Note that this syntax will work for "__radd__
", since it calls "__add__
" and not itself (so no recursion).
Son-Hai Nguyen
2,481 PointsSon-Hai Nguyen
2,481 PointsThanks Stephen. So is it kind of how python works? I mean like it will always calls for the the method add? Or the current method which is currently defined?
Steven Parker
231,248 PointsSteven Parker
231,248 PointsIt always calls calls "add" when a "+" operation is being performed and an item of this class is the left operand.