幻狐岚 2015-02-13 09:08 采纳率: 0%
浏览 1784
已采纳

关于python描述符和私有属性的问题

Person类如下
class Person(object):
def setProperty(self,attribute,value):
print 'set this person instance with attribute %s and value %s'%(attribute,value)
setattr(self,'
'+attribute,value.title())

def _getProperty(self,attribute):
    print "Getting property: %s"%attribute
    return getattr(self,'_'+attribute)

def addProperty(self,attribute):
    setter = lambda self,value:self._setProperty(attribute,value)
    getter = lambda self:self._getProperty(attribute)
    #construct property attribute and add it to the class
    #setattr(object, name, value)
    setattr(self.__class__,attribute,property(fset=setter,fget=getter,doc='Auto-generrated method'))
    print "new attribute %s has been added successfully"%attribute

p=Person()
p.addProperty('name')
#print dir(Person())
p.name = 'shit'
#print dir(Person())
print p.name

为什么当我把 setattr(self,'_'+attribute,value.title())中的'_'+去掉时,python会不断对person.name进行赋值操作,像这样。。

set this person instance with attribute name and value shit(注意这个shit是小写)
set this person instance with attribute name and value Shit
set this person instance with attribute name and value Shit
set this person instance with attribute name and value Shit
............

  • 写回答

1条回答 默认 最新

  • MarvinHe 2015-02-26 09:22
    关注

    因为 attribute 的 setter 被你复写了; setattr( attribute, value) 实际调用的是 setProperty(attribute, value); 互相调用,死循环;

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?