2017-03-13 30 views
0

我正在創建一個獲取股票數據的python模塊。基於Python中的字典的動態方法

我有一本字典:

{'StockSymbol': 'AMD', 'LastTradeTime': '4:00PM EST', 'ChangePercent': '+0.58', 'ID': '327', 'LastTradeDateTimeLong': 'Mar 10, 4:00PM EST', 'Index': 'NASDAQ', 'LastTradeWithCurrency': '13.91', 'LastTradeDateTime': '2017-03-10T16:00:02Z', 'LastTradePrice': '13.91', 'LastTradeSize': '0', 'PreviousClosePrice': '13.33'} 

目前我有11種方法,如:

class Stock(object): 

    def getSymbol(): 
     return self.data['StockSymbol'] 

    def getLastTradeTime(): 
     return self.data['LastTradeTime'] 

    ........ 

我用它作爲:

google = Stock('GOOG') 
print(google.getLastTradeTime()) //4:00PM EST 

我的問題是,是否有可能動態生成這些方法?

所以我可以做google.getLastTradeSize()等沒有定義它們。

這裏是一個Python小提琴:https://repl.it/GSG1

+1

我什至不明白爲什麼你有方法只是圍繞字典查找包裝。 – TigerhawkT3

+0

你可以編寫__getattribute__方法並返回一個可調用的? – lctr30

+0

@ TigerhawkT3這個想法是批量編輯數值(例如,將所有unix時間轉換成數千和數百萬等等)。 – WhatisSober

回答

3

在Python中有一個名爲一堆設計模式,它的工作原理是這樣的,我相信它可以解決你的問題:

class Bunch(dict): 
    def __init__(self, *args, **kwargs): 
     super(Bunch, self).__init__(*args, **kwargs) 
     self.__dict__ = self 


    def __getattribute__(self, item): 
     try: 
      return object.__getattribute__(self, item) 
     except: 
      return None 

my_dict = {'StockSymbol': 'AMD', 'LastTradeTime': '4:00PM EST', 'ChangePercent': '+0.58', 'ID': '327', 
      'LastTradeDateTimeLong': 'Mar 10, 4:00PM EST', 'Index': 'NASDAQ', 'LastTradeWithCurrency': '13.91', 
      'LastTradeDateTime': '2017-03-10T16:00:02Z', 'LastTradePrice': '13.91', 'LastTradeSize': '0', 
      'PreviousClosePrice': '13.33'} 

obj = Bunch(**my_dict) 
print obj.StockSymbol 
print obj.LastTradeTime 
print obj.key_not_exist 

而我們得到:

AMD 

4:00PM EST 

None 

因此,您不必定義所謂的gettter方法,就像您在Java/C++中所做的一樣;

PS:在一個真實的項目中,你也可以繼承這個Bunch類。

+0

太棒了。如果找不到密鑰,是否有可能返回null([])? – WhatisSober

+1

@WhatisSober,是的,這是可行的,我已經在代碼中添加了相關的方法。如果這是你想要的,我會很感激。 –