Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error in setter in class maximum recursion depth

My friends, as far as I check my syntax code is correct, comrades, thank you for your help

My code:

class person:
   def __init__(self,name,family):
       self.name = name
       self.family = family
   @property
   def fullname(self):
      return f"{self.name} {self.family}"

class user(person):
       def __init__(self,name,family,age):
            super().__init__(name,family)
            self.age = age  
       @property
       def age(self):
              return self.age
       @age.setter
       def age(self,age_new):
              self.age = age_new

emanuel = user("emanuel","victor",15)

print(emanuel.fullname)

print(emanuel.age)

emanuel.age = 20

print(emanuel.age)

Error:
Comrades, I am training and I get a lot of errors, but what can I really do about this one?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Traceback (most recent call last):
  File "main.py", line 20, in <module>
    emanuel = user("emanuel","victor",15)
  File "main.py", line 12, in __init__
    self.age = age  
  File "main.py", line 18, in age
    self.age = age_new
  File "main.py", line 18, in age
    self.age = age_new
  File "main.py", line 18, in age
    self.age = age_new
  [Previous line repeated 994 more times]
RecursionError: maximum recursion depth exceeded

>Solution :

You need to use an attribute with a different name to your property. Otherwise when you try to set self.age from inside the setter method, the setter calls itself.

Try this instead:

class User(Person):
    def __init__(self, name, family,age):
        super().__init__(name, family)
        self._age = age  
    
    @property
    def age(self):
        return self._age
    
    @age.setter
    def age(self, age_new):
        self._age = age_new
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading