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 Object-Oriented Python Advanced Objects Math

Son-Hai Nguyen
Son-Hai Nguyen
2,481 Points

What 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
Steven Parker
210,424 Points

When 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
Son-Hai Nguyen
2,481 Points

Thanks 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
Steven Parker
210,424 Points

It always calls calls "add" when a "+" operation is being performed and an item of this class is the left operand.