繁体   English   中英

在python类中使用configparser,好还是坏?

[英]using configparser in python class, good or bad?

在类方法中使用ConfigParser是不好的做法吗? 这样做将意味着该类随后被绑定到配置上,而不是那么容易重用,但是意味着方法中的输入参数更少,尤其是在参数必须向下传递多层的情况下,我会感到混乱。

是否有很好的选择(除了仅将配置值作为方法参数传递外)? 还是人们发现的特定模式对此很有效?

例如

# get shared config parser configured by main script
from utils.config_utils import config_parser

class FooClass(object):

    def foo_method(self):
        self._foo_bar_method()

    def _foo_bar_method(self):
        some_property = config_parser.get("root", "FooProperty")
        ....

如果您在单个类中需要大量参数,这可能是您试图对该类进行过多处理的症状(请参见SRP

如果确实确实需要一些配置选项,而这些配置选项太多了,无法提供一个简单的类作为参数,我建议将配置抽象为一个单独的类,并将其用作参数:

class Configuration(object):
    def __init__(self, config_parser):
        self.optionA = config_parser.get("root", "AProperty")
        self.optionB = config_parser.get("root", "BProperty")
        self.optionX = config_parser.get("root", "XProperty")

    @property
    def optionY(self):
        return self.optionX == 'something' and self.optionA > 10


class FooClass(object):
    def __init__(self, config):
        self._config = config

    def _foo_bar_method(self):
        some_property = self._config.optionY
        ....

config = Configuration(config_parser)
foo = FooClass(config)

通过这种方式,您可以重用您的配置抽象,甚至可以从同一配置解析器出于不同目的构建不同的配置抽象。

您甚至可以改进配置类,使其具有更具声明性的方式来将配置属性映射到实例属性(但这是更高级的主题)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM