2013-02-07 27 views
3

我正在读取property(),我知道属性访问是通过property()中指定的方法进行的。 但是当执行下面的代码时,我得到了“RuntimeError:超出最大递归深度”。当“属性”应用于实例变量“self.x”时,“超出最大递归深度”

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 

    def dellx(self): 
     print "deleting" 
     return 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 

以这种方式应用财产是不可能的。因为它在'self.x'改为self._x和self.__ x时运行良好。

回答

10

的错误是由于以下无限递归循环:您已定义的属性x与使用gettxsettxdeltx访问方法,但访问方法自己尝试访问属性x(即自称)。

你应该写的代码大致如下:

class Property(object): 

    def __init__(self): 
     self.__x = "Raj" # Class private 

    def gettx(self): 
     print "getting x" 
     return self.__x 

    def settx(self, val): 
     print "Setting x" 
     self.__x = val 

    def dellx(self): 
     print "deleting" 
     return self.__x 

    x = property(gettx, settx, dellx, "I'm object property") 
+0

是的。它的作品自我.__ x和self._x。如果我想要property()作为“公共”实例变量来控制它的访问,会怎样? – rajpy

+0

属性本身(即您的示例中的'x')是公共属性。它需要一个不同的私有存储,但是(即'_x'或'__x')。所以你要控制公共属性('x')并隐藏存储('_x'或'__x')。合理? – isedev

+0

属性名称“x”也是变量混淆了我的名字。 感谢您指出。 – rajpy

0

按照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.

所以,你的代码行self.x = "Raj"基本调用该方法settx(self, val)。在该方法中,self.x = val行再次调用settx(self, val)方法,该方法又调用settx(self, val)。因此,我们有一个无限循环。

因此,设置属性值的正确方法是self._x = value

正确的代码:

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 

输出:

p.x getting x 
Raj 
Setting x 
p.x: getting x 
R 
相关问题