如何从 dict 继承的 class 自动更新键?

How to auto update keys from a class inherited from dict?

我有一个 class 继承自 dict class。在下面的示例中,我定义了两个键 'x' 和 'x2',默认值为

class myClass(dict):
   def __init__(self,*arg,**kw):
      super(myClass, self).__init__(*arg, **kw)
      self['x']=2
      self['x2']=self['x']*self['x']

我希望它们以某种方式链接,这样如果我修改 'x''x2' 将由 x*x 更新,如果我修改 'x2',则'x' 更新为 sqrt(x)

我找到了 post 解释了 class 属性的解决方案:In class object, how to auto update attributes?

但是,我无法找到一种方法来扭曲此示例以使其适用于字典键。有人知道怎么做吗?

谢谢!

对于子类化字典,建议使用 collections.UserDict 中的子类,而不是 dict。使用 UsedDict,您的所有内容都存储在 data 变量中。 Manual pages here.

对于所需的功能,您可以重新定义 __setitem__ 特殊方法:

import math
from collections import UserDict

class myClass(UserDict):
    def __init__(self,*arg,**kw):
        super(myClass, self).__init__(*arg, **kw)

        self.data['x'] = 2
        self.data['x2']= self['x'] * self['x']

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        if key == 'x':
            self.data['x2'] = value * value
        elif key == 'x2':
            self.data['x2'] = math.sqrt(value)

c = myClass()
print(c['x'])
print(c['x2'])
print('-' * 80)
c['x'] = 4
print(c['x'])
print(c['x2'])
print('-' * 80)
c['x2'] = 9
print(c['x'])
print(c['x2'])

输出:

2
4
--------------------------------------------------------------------------------
4
16
--------------------------------------------------------------------------------
4
3.0