を使用して設定をロードしConfigParser
、すべてのアイテムを辞書として取得し、それらをオブジェクトの属性として設定する単純なオブジェクトをPythonで作成しようとしています。
メソッドを含めない場合、これは機能するよう__setattr__
です。「settings.top_travel」を呼び出して、回答を返すことができます。ただし、を入れてみると__setattr__
エラーが発生するようです。
かなり再帰的に見えるので、などGet
を呼び出しSet
ていると思います。属性の設定部分で、構成ファイルに書き戻したいと思います。したがって、設定属性の1つが変更されると、それは元のファイルに戻されます。
以下にコードとエラーがあります。
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 <module>
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