3

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

如果我不包含__setattr__方法,这似乎可行。我可以打电话给“settings.top_travel”并得到答案。但是,一旦我尝试输入 a __setattr__,我似乎就会收到错误消息。

它看起来相当递归,所以我假设Get正在调用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 <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

__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 回答
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 回答
-3

无论你用 ConfigParser 做什么聪明的事情都是无限递归的。我无法确定,因为我没有看到代码,但如果您使用递归,请确保涵盖所有基本情况。

于 2010-11-26T16:18:36.077 回答