【发布时间】: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