【问题标题】:How can I associate sections with classes in a config file?如何将部分与配置文件中的类相关联?
【发布时间】:2017-08-25 16:11:26
【问题描述】:

假设我有一个程序来检索不同类型动物的信息。我有在命名元组中表示的动物类型,我从配置文件构造:

config.ini

[Cat]
limb_count = 4
size_class = Small

animals.py

AnimalData = namedtuple('Animal', 'type limb_count size_class')

现在,我从不同的站点为每只动物抓取数据,所以我的AnimalStatsRepository 设置如下:

class AnimalStatsRepository(object):
    def __init__(self):
        self._queries_by_animal = {
            'Cat': CatQuery(),
            'Dog': DogQuery(),
            'Zebra': ZebraQuery()
        }    

    def get_birthrate(self, animal):
        return self._queries_by_animal[animal.type].get_birthrate()
        # And also do database stuff that's not relevant to the question

我希望能够根据我从配置文件中读取的任何动物数据在运行时设置_queries_by_animal 字典。所以像:

class AnimalStatsRepository(object):
    def __init__(self, animals_data):
        self._queries_by_animal = {} 
        for animal in animals_data:
            self._queries_by_animal[animal.type] = ??   

我可能可以通过一些邪恶的反射黑客来获得我想要的东西。但是有没有更好的方法来解决这个问题?

【问题讨论】:

    标签: python dependency-injection configuration


    【解决方案1】:

    可以使用工厂方法从配置文件中的文本创建正确的查询。实现可能如下所示:

    def animal_query_factory(animal_name):
        if animal_name == 'Cat':
            return CatQuery()
        if animal_name == 'Dog':
            return DogQuery()
        raise NotImplementedError('Unable to handle animal: {}'.format(animal_name))
    

    【讨论】:

      猜你喜欢
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-01
      相关资源
      最近更新 更多