幻狐岚 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); 互相调用,死循环;

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题