在Python类中使用configparser,值得吗?
在类的方法中使用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")
....
1 个回答
1
如果你在一个类里需要很多参数,这可能说明你这个类的功能太复杂了(可以参考一下单一职责原则)。
如果确实有必要使用很多配置选项,而这些选项又不适合简单的类作为参数传入,我建议你把这些配置抽象成一个单独的类,然后把这个类作为参数使用:
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)
这样一来,你就可以重复使用这个配置类,甚至可以从同一个配置解析器中为不同的目的构建不同的配置类。
你还可以进一步改进这个配置类,让它以更直观的方式将配置属性映射到实例的属性上(不过这就属于更高级的内容了)。