3

を使用して設定をロードし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
4

3 に答える 3

5

問題は、self.configurationを設定すると呼び出されることですself.__setattr__

__setattr__スーパークラスの呼び出しへの割り当てを変更することで、これを回避できます。

class settingsFile(object):

    def __init__(self):
        ...
        # Return all the "config" section as a list and convert to a dictionary
        object.__setattr__(self, 'configuration', dict(configuration.items("config")))
于 2010-11-26T16:21:33.957 に答える
5

__setattr__で始まらない属性を排他的にし、構成をself._configuration'_'に格納してから、名前がアンダースコアで始まるオプションを構成ファイルが受け入れないという要件を追加します。

def __setattr__(self, attribute, value):
     if attribute.startswith('_'):
          super(settingsFile, self).__setattr__(attribute, value)
          return
     # Clever stuff happens here
于 2010-11-26T16:34:19.370 に答える
-3

ConfigParserで行っている巧妙な作業は、無限に繰り返されます。コードが表示されないためわかりませんが、再帰を使用している場合は、すべての基本ケースをカバーしていることを確認してください。

于 2010-11-26T16:18:36.077 に答える