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 trialLiang Junwen
582 PointsWhy 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
Treehouse Moderator 68,457 PointsIn 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
582 PointsLiang Junwen
582 PointsHi, 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
Treehouse Moderator 68,457 PointsChris Freeman
Treehouse Moderator 68,457 PointsBecause of the
@property
and the@diameter.setter
decorators, whenever the attributeself.diameter
is assigned, the assignment is replaced by a call to setter method.So, this
To see this in action try
The loop will be broken as the recursion limit is reached ( ~1000)
Liang Junwen
582 PointsLiang Junwen
582 PointsThanks for your follow up response, I got it!