我试图用python编写一个简单的对象,它将使用
ConfigParser
,将所有项作为字典获取,然后将这些项设置为对象的属性。
如果我
不要
包括
__setattr__
方法。我可以打电话给“settings.top_travel”得到答案。但是,只要我试着
__塞塔特__
,我好像搞错了。
它看起来相当递归,所以我假设
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
错误:
Traceback (most recent call last):
File "/home/stuff/Documents/Software/Python/dBControllers v2/dBControllers.py", line 52, in
settings = settingsFile()
File "/home/stuff/Documents/Software/Python/dBControllers v2/dBControllers.py", line 37, in __init__
self.configuration = dict(configuration.items("config"))
File "/home/stuff/Documents/Software/Python/dBControllers v2/dBControllers.py", line 47, in __setattr__
print self.configuration[attr], " is now ", value
File "/home/stuff/Documents/Software/Python/dBControllers v2/dBControllers.py", line 44, in __getattr__
return self.configuration[attr]
File "/home/stuff/Documents/Software/Python/dBControllers v2/dBControllers.py", line 44, in __getattr__
return self.configuration[attr]
......
RuntimeError: maximum recursion depth exceeded