python setattr无限递归_在python中引入setattr时出现递归错误

我试图用python编写一个简单的对象,它将使用ConfigParser加载设置,将所有项作为字典获取,然后将这些项设置为对象的属性。在

如果我不包含__setattr__方法,这似乎是可行的。我可以打电话”settings.top_旅行“把答案拿回来。但是,一旦我尝试输入__setattr__,我似乎得到了一个错误。在

它看起来相当递归,所以我假设Get正在调用Set,等等。在set属性部分,我希望让它写回配置文件。因此,每当设置属性中的一个发生更改时,它就会被存储回它的来源文件中。在

下面您将找到代码和错误。在import ConfigParser

class settingsFile(object):

def __init__(self):

"""

Reloads the configuration file and returns a dictionary with the

settings :

[config]

top_travel = 250

"""

# Create a configuration object and read in the file

configuration = ConfigParser.ConfigParser()

configuration.read('config/config.cfg')

# Return all the "config" section as a list and convert to a dictionary

self.configuration = dict(configuration.items("config"))

def refresh(self):

self.__init__()

def __getattr__(self, attr):

return self.configuration[attr]

def __setattr__(self, attr, value):

print attr, " is now ", value

# Do some clever storing with ConfigParser

if __name__ == "__main__":

settings = settingsFile()

print settings.top_travel

settings.top_travel = 600

print settings.top_travel

错误:

^{pr2}$

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值