我正在創建一個獲取股票數據的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
我什至不明白爲什麼你有方法只是圍繞字典查找包裝。 – TigerhawkT3
你可以編寫__getattribute__方法並返回一個可調用的? – lctr30
@ TigerhawkT3這個想法是批量編輯數值(例如,將所有unix時間轉換成數千和數百萬等等)。 – WhatisSober