I am new to OOPS and testing property decorator. This is working fine with the string type but for an integer, it is failing with Maximum recursion error when property for age.Did anyone come across recursion code?. I have seen a post to add an object in the syntax for the class but it didn't help much.
class person(object):
def __init__(self, first, last, age=0):
self.first = first
self.last = last
self.age = age
@property
def e_mail(self):
self.email = self.first+'.'+self.last+'@example.com'
return self.email
@e_mail.setter
def e_mail(self,first,last):
self.first=first
self.last=last
@property
def age(self):
return self.age
@age.setter
def age(self,age):
self.age = age * 10
x=person('john', 'abc', 5)
print(x.first)
print(x.last)
print(x.e_mail)
print(x.__dict__)
x.first='jj'
x.age=10
print(x.__dict__)
Error message:
Traceback (most recent call last):
File "C:/Python/022618/test.py", line 30, in <module>
x=person('john', 'abc', 5)
File "C:/Python/022618/test.py", line 7, in __init__
self.age = age
File "C:/Python/022618/test.py", line 27, in age
self.age = age * 10
File "C:/Python/022618/test.py", line 27, in age
self.age = age * 10
File "C:/Python/022618/test.py", line 27, in age
self.age = age * 10
[Previous line repeated 493 more times]
RecursionError: maximum recursion depth exceeded
Process finished with exit code 1
I have found some additional information on the stack overflow on the setter behavior and this works. This also explains why recursion is happening. infinite recursion in python3.3 setter
Based on the suggestion, I have updated my code..Thank you for taking a look at it.
Here is the updated snippet
@property
def age(self):
return self._age
@age.setter
def age(self,val):
self._age = val * 10