“maximum recursion depth exceeded” when “property” is applied to instance variable “self.x”

后端 未结 2 1829
既然无缘
既然无缘 2021-01-03 07:44

I was reading property(), which I understand is attribute access goes through the method specified in property(). But I got \"RuntimeError: maximum recursion depth exceeded\

2条回答
  •  臣服心动
    2021-01-03 08:06

    According to the python docs:

    If c is an instance of C, c.x will invoke the getter, c.x = value will invoke the setter and del c.x the deleter.

    So, your code line self.x = "Raj" essentially calls the method settx(self, val). Within that method the line self.x = val again calls the settx(self, val) method which in turn again calls the settx(self, val). Thus, we have an infinite loop.

    So, the correct way to set the value of the property is self._x = value.

    Correct code:

    class Property(object):
        def __init__(self):
            self._x = 'Raj'
    
        def gettx(self):
            print "getting x"
            return self._x
    
        def settx(self, val):
            print "Setting x"
            self._x = val #stores the value in _x. writing self.x = val would cause an infinite loop
    
        def dellx(self):
            print "deleting"
            del self._x    
    
        x = property(gettx, settx, dellx, "I'm object property")
    
    p = Property()
    print "p.x", p.x
    p.x = "R"
    print "p.x:", p.x
    

    Output:

    p.x getting x
    Raj
    Setting x
    p.x: getting x
    R
    

提交回复
热议问题