I am learning how to create classes in python where when modifying attribute 1 will change attribute 2. For instance a circle with an attribue radius.
class Circle():
def __init__(self,radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
self.radius = value
@property
def area(self):
return 3.14*self.radius*self.radius
And this happens:
c = Circle(3)
c.area
All fine. but now:
c.radius = 56
print(c.area)
gives:
RecursionError: maximum recursion depth exceeded
The question is why? What is the way to force recalculation of other attributes when one is changed?
I have consulted several answers: Python: modifying property value How do you change the value of one attribute by changing the value of another? (dependent attributes)
EDIT: According to some answers (see bellow) I am in an infinite loop. So I delete the part of the setter. I remain with:
class Circle():
def __init__(self,radius):
self._radius = radius
@property
def radius(self):
return self._radius
@property
def area(self):
return 3.14*self.radius*self.radius
What happens then is:
c = Circle(3)
c.radius = 30
error: AttributeError: can't set attribute