Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/361.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python中基于dict的动态方法_Python_Python 3.x_Oop - Fatal编程技术网

python中基于dict的动态方法

python中基于dict的动态方法,python,python-3.x,oop,Python,Python 3.x,Oop,我正在创建一个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

我正在创建一个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提琴:

在Python中有一个名为bunch的设计模式,它是这样工作的,我相信它可以解决您的问题:

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
因此,您不必像在Java/C++中那样定义所谓的getter方法


PS:在实际项目中,您也可以继承这个Bunch类。

在Python中,有一个名为Bunch的设计模式,它是这样工作的,我相信它可以解决您的问题:

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
因此,您不必像在Java/C++中那样定义所谓的getter方法


PS:在实际项目中,您也可以继承这个Bunch类。

我甚至不明白为什么您的方法只是围绕字典查找的包装。您可以编写getattribute方法并返回可调用的?@TigerhawkT3想法是批量编辑值(例如,转换所有unix时间,将数字更改为数千和数百万等)。这与制作一堆毫无意义的包装器有什么关系?我甚至不明白为什么在字典查找中会有只包装器的方法。您可以编写getattribute方法并返回可调用的?@TigerhawkT3想法是批量编辑值(例如,转换所有unix时间,将数字更改为数千和数百万等)。这与制作一堆毫无意义的包装器有什么关系?太棒了。是否可以返回null([])如果找不到密钥?@WhatisSober,是的,这是可行的,我已经在代码中添加了相关的方法。如果这是您想要的,我将不胜感激。太棒了。可以返回null([])吗如果找不到密钥?@WhatisSober,是的,这是可行的,我已经在代码中添加了相关的方法。如果这是你想要的,我将不胜感激。