【问题标题】:Reference a dict as a class attribute引用 dict 作为类属性
【发布时间】:2016-04-06 00:50:05
【问题描述】:

如何将字典的引用设置为类属性的一部分,即使在其值更新后?

live = {'APPL': {'bid': 41, 'ask': 43}}
extras = {'name': 'apple', 'country': 'us', 'currency': 'usd'}

class myClass:
 def __init__(self, live_data, extra_data):
  self.__dict__ = live_data
  self.__dict__.update(extra_data)

 def update(self, extra_data):
  self.__dict__.update(extra_data)


symbol = myClass(live['APPL'], extras)

如果变量 'live' 更新,一切正常。
如果变量 'extras' 被更新,实例属性将失去它的引用。

正在更新字典数据...

live['APPL']['bid'] = 40
live['APPL'].update({'ask': 44})
extras['country'] = 'uk'
extras.update({'currency': 'gbp'})

实例“符号”未正确更新

In: symbol.bid
Out: 40
In: symbol.ask
Out: 44
In: symbol.country
Out: 'us'
In: symbol.currency
Out: 'usd'

如何保持对字典的属性引用,一旦新数据到达,字典就会不断更新其值?

【问题讨论】:

    标签: python class dictionary reference attributes


    【解决方案1】:

    不要修改self.__dict__,而是定义一个__getattr__()方法:

    class myClass:
        def __init__(self, live_data, extra_data):
            self._live = live_data
            self._extra = extra_data
    
        def __getattr__(self, name):
            if name in self._extra:
                return self._extra[name]
            elif name in self._live:
                return self._live[name]
            else:
                raise AttributeError("No attribute: {}".format(name)
    

    【讨论】:

    • 它工作得完美无缺,但是在每次调用时使用这种方法比以前的工作要慢得多。 1.24 µs per loop vs 164 ns per loop 因为此代码每秒运行多次,所以欢迎任何允许类属性保持对 dict 项的引用的想法或建议。
    猜你喜欢
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多