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 Special Methods

Liang Junwen
Liang Junwen
582 Points

Why this code get RecursionError: maximum recursion depth exceeded?

The code:

class Circle(object):
    def __init__(self, radius):
        self.radius = radius

    @property
    def diameter(self):
        return self.radius * 2

    @diameter.setter
    def diameter(self, value):
        self.diameter = value


circle = Circle(22)
circle.diameter += 3

Why I get RecursionError: maximum recursion depth exceeded? Thank you~~

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,082 Points

In the code:

    @diameter.setter
    def diameter(self, value):
        self.diameter = value

self.diameter = value Is setting the value of the attribute diameter, which called the setter method.... hence the recursive loop.

Perhaps you want self.radius = value / 2

Post back if you need more help. Good luck!!!

Liang Junwen
Liang Junwen
582 Points

Hi, Chris! Thank you for your explanation. I know "self.radius = value / 2" is the right answer, but I don't understand why "self.diameter = value" will cause RecursionError, could you please explain more deeply about reason in underlying logic? Thanks again!

Chris Freeman
Chris Freeman
Treehouse Moderator 68,082 Points

Because of the @property and the @diameter.setter decorators, whenever the attribute self.diameter is assigned, the assignment is replaced by a call to setter method.

So, this

    @diameter.setter
    def diameter(self, value):
        self.diameter = value

    # effectively becomes

    def diameter(self, value):
        diameter(self, value)

To see this in action try

def recursive_loop(value):
    value += 1
    print(value)
    recursive_loop(value)

recursive_loop(0)

The loop will be broken as the recursion limit is reached ( ~1000)

Liang Junwen
Liang Junwen
582 Points

Thanks for your follow up response, I got it!