Error: "Maximum recursion depth exceeded while calling a Python object"

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 it 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
    
asked by anonymous 18.10.2017 / 05:23

1 answer

3

The error is due to you being set a property that has the same name as your setter , and your method:

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

Whenever this value changes it returns to call the setter, which has the same property name (and method), and goes into recursion.

To avoid this, you conventionally set _ 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 __init__ make self._x = x instead of what we have. Thus, in the creation of the object ( p = Ponto(32) ), self._x = x is not assumed by setter .

Further reading

    
18.10.2017 / 10:29