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