ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

如何使用__setattr__和__getattr__来映射INI值?

2019-06-11 00:49:33  阅读:198  来源: 互联网

标签:python configuration-files


我想将INI文件映射为python对象.所以如果文件有:

[UserOptions]
SampleFile = sample.txt
SamplePort = 80
SampleInt = 1
Sample = Aja
SampleDate = 10/02/2008

然后我想:

c = Configuration('sample.ini')

c.UserOptions.SamplePort = 90

我正在寻找setattr,但我得到一个递归错误.

这就是我所拥有的:

class Configuration:
    def __init__ (self, fileName):
        cp = SafeConfigParser()
        cp.read(fileName)
        self.__parser = cp
        self.fileName = fileName

    def __getattr__ (self, name):
        if name in self.__parser.sections():
            return Section(name, self.__parser)
        else:
            return None

    def __str__ (self):
        p = self.__parser
        result = []
        result.append('<Configuration from %s>' % self.fileName)
        for s in p.sections():
            result.append('[%s]' % s)
            for o in p.options(s):
                result.append('%s=%s' % (o, p.get(s, o)))
        return '\n'.join(result)

class Section:
    def __init__ (self, name, parser):
        self.__name = name
        self.__parser = parser

    def __getattr__ (self, name):
        if self.__dict__.has_key(name):       # any normal attributes are handled normally
            return __getattr__(self, item)
        else:
            return self.__parser.get(self.name, name)

    def __setattr__(self, item, value):
        """Maps attributes to values.
        Only if we are initialised
        """
        if self.__dict__.has_key(item):       # any normal attributes are handled normally
            dict.__setattr__(self, item, value)
        else:
            self.__parser.set('UserOptions',item, value)

现在我想知道为什么在self .__ parser.set(‘UserOptions’,item,value)我得到了错误.我读了Python文档,我不知道该怎么做.我怀疑我需要存储带有字段名称的字典,然后先看一下但是如何?

解决方法:

您正在尝试根据要求获取这些部分.但是迭代部分和选项并在__init__中将它们添加为属性要容易得多.我编辑了我的例子来支持setattr.您解决了问题here您在__setattr__中分配属性,而您应该使用__dict__

from ConfigParser import  SafeConfigParser

class Section:
    def __init__(self, name, parser):
        self.__dict__['name'] = name
        self.__dict__['parser'] = parser

    def __setattr__(self, attr, value):
        self.__dict__[attr] = str(value)
        self.parser.set(self.name, attr, str(value))

class Configuration(object):
    def __init__(self, fileName):
        self.__parser = SafeConfigParser()
        self.__parser.read(fileName)
        self.fileName = fileName
        for section in self.__parser.sections():
            setattr(self, section, Section(section, self.__parser))
            for option in self.__parser.options(section):
                setattr(getattr(self, section), option,
                        self.__parser.get(section, option))

    def __getattr__(self, attr):
        self.__parser.add_section(attr)
        setattr(self, attr, Section(attr, self.__parser))
        return getattr(self, attr)

    def save(self):
        f = open(self.fileName, 'w')
        self.__parser.write(f)
        f.close()

c = Configuration('config.ini')

print dir(c) -> will print all sections
print dir(c.UserOptions) -> will print all user options
print c.UserOptions.sampledate

c.new.value = 10
c.save()

标签:python,configuration-files
来源: https://codeday.me/bug/20190610/1214878.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有