2017-08-25 24 views
0

假設我有一個程序來檢索不同類型動物的信息。我有一個名爲元組所代表的動物種類,這是我從一個配置文件構建:如何將部分與配置文件中的類關聯?

的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] = ?? 

我可以得到我想要的一些邪惡的反思黑客攻擊。但是有沒有更好的方法來解決這個問題?

回答

0

工廠方法可用於從配置文件中的文本創建正確的查詢。實現可能如下所示:

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)) 
相關問題