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

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,441 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,441 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!