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
............
因為 attribute 的 setter 被你復寫了; setattr( attribute, value) 實際調用的是 setProperty(attribute, value); 互相調用,死循環;