Error: "Maximum recursion Depth exceeded while Calling a Python Object"

Asked

Viewed 5,780 times

1

class Ponto(object):
    def __init__(self, x):
        self.x = x
    @property
    def x(self):
        return self.x
    @x.setter
    def x(self, valor):
        self.x = valor

When I run the script generates:

Traceback (most recent call last):
 File "<pyshell#0>", line 1, in <module>
   x = Ponto(2)
 File "C:/Users/ThiagoDEV/AppData/Local/Programs/Python/Python36/OOP39.py", line 3, in __init__
   self.x = x
 File "C:/Users/ThiagoDEV/AppData/Local/Programs/Python/Python36/OOP39.py", line 9, in x
   self.x = valor
 File "C:/Users/ThiagoDEV/AppData/Local/Programs/Python/Python36/OOP39.py", line 9, in x
   self.x = valor
 File "C:/Users/ThiagoDEV/AppData/Local/Programs/Python/Python36/OOP39.py", line 9, in x
   self.x = valor
 [Previous line repeated 491 more times]
RecursionError: maximum recursion depth exceeded while calling a Python object
  • 1

    Not the identation is correct is that in the hours of posting did not give tabulation

1 answer

4


The mistake is because you’re settar a property that bears the same name as yours setter, and its method:

@x.setter
def x(self, valor):
    self.x = valor # valor de x muda aqui

Whenever this value changes it returns to call Setter, which has the same name as the property (and method), and enters recursiveness.

To avoid this, conventionally put _ before a new property with the same name:

class Ponto(object):
    def __init__(self, x):
        self.x = x
    @property
    def x(self):
        return self._x
    @x.setter
    def x(self, valor):
        self._x = valor
        print('x mudou para', self.x) # self.x também muda

p = Ponto(32)
p.x = 10
p.x = 15
print(p.x)

DEMONSTRATION

Note that you can also on __init__ do self._x = x instead of what we have. In this way, in the creation of the object (p = Ponto(32)), self._x = x is not assumed by setter.

Further reading

Browser other questions tagged

You are not signed in. Login or sign up in order to post.