簡體   English   中英

dict作為參數化python類的方法的替代方法是什么?

[英]What is the alternative to dict as way to parameterize python class?

我通常會在所使用的代碼庫周圍看到以下python代碼:

class A:
    def do_something(self):
        pass

class B:
    def do_something(self):
        pass


class C:
    _magic_dict = {'option1' : A, 'option2' : B}

   def do_something_else(self, option):
       # call some other methods, functiosn
       my_option = _magic_dict['option']()
       my_option.do_something()

       self.do_more_things(my_option)

因此,基本思想是使C類對A或B通用。這是常見的做法嗎? 我覺得這是對指令的過度使用,並且一切(在本例中為類)都是可以傳遞的對象。

對於更具體的問題,以下示例可能會有所幫助。 有一個類負責獲取給定的度量標准對象,該類最終是持有該度量標准類型信息的對象的字典。 有一個統計報告器,它將使用給定的度量對象,選擇要報告的數據類型(假設是dict中的一項),並以漂亮的格式輸出。 所以:

class FoodMetric:
    def __init__(self, path_to_my_stock_files):
        self._path = path_to_my_stock_files
        self._data = {}

    def parse(self):
        # let's assume that after parsing the files, the following data would have been obtained:
        # self.data = {'cheese' : {'cheddar' : 10, 'goat' : 20}}

class WoodFastenerMetric:
    def __init__(self, path_to_my_stock_files):
        self._path = path_to_my_stock_files
        self._data = {}

    def parse(self):
        # let's assume that after parsing the files, the following data would have been obtained:
        # self.data = {'nails' : {'round' : 10, 'oval' : 20}}

class StatsReporter:

    _magic_dict = {'food' : (FoodMetric, ['column1', 'column2'], 'cheese')
                   'wood_fastener' : (WoodFastener, ['columnA', 'columnB'], 'nail')
                  }      

    def present_data(metric_type):
        the_class, columns, data_set_name = _magic_dict(metric_type)
        metric = the_class(self._path) # assume I have the path for the files here
        metric.parse()
        print(self._convert_to_table(metric, columns, data_set_name))

我確實有一個替代實現,它通過將A或B的一個實例傳遞給C來創建C,因此消除了C中的字典查找。

還有什么其他選擇,還是問題中所述的解決方案是在python中解決此問題的常用方法?

PS:我希望這個例子可以使意圖更加清楚。

使用與原始問題相同的類和方法名稱,並且缺少有關要解決的實際問題的任何信息,我將代碼重構為以下內容:

class C:
   def do_something_else(self):
       self.do_something()
       self.do_more_things()

    def do_something(self):
        raise NotImplementedError()

class A(C):
    def do_something(self):
        pass

class B(C):
    def do_something(self):
        pass

def make_instance(option):
    return {'option1' : A, 'option2' : B}[option]()

instance = make_instance(option)
instance.do_something_else()

使用這種方法,設計很清楚: C實現了通用功能,而AB是其專門化功能。

剩下的唯一丑陋的部分是make_instance函數,它可能也可能更好,但是不是問題的表達方式,因為不清楚option來自何處。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM