在python中引入setattr时的递归错误

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

如果我不包含__setattr__方法,这似乎有效.我可以调用“settings.top_travel”并获得答案.但是,一旦我尝试放一个__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

错误:

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

解决方法:

问题是设置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")))
上一篇:java – 在元素上设置命名空间属性


下一篇:Thymeleaf中获取作用域中的数据