通过dict.update()继承静态dict

时间:2014-03-21 00:27:18

标签: python inheritance dictionary

我的应用程序模型中的子类从超类继承静态属性(存储为字典),每个子类使用update()向其添加字段自己的静态字段。但这并没有像我预期的那样发挥作用。这是简单的版本:

In [19]: class A(object):
    s = {1:1} 

In [20]: class B(A):
    s = A.s.update({2:2})

In [21]: class C(B):
    s = B.s.update({3:3})

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-21-4eea794593c8> in <module>()
----> 1 class C(B):
      2     s = B.s.update({3:3})
      3 

<ipython-input-21-4eea794593c8> in C()
      1 class C(B):
----> 2     s = B.s.update({3:3})
      3 

AttributeError: 'NoneType' object has no attribute 'update

然而,当我将字段连接到每个子类中的静态列表时,这个DID工作。我错过了什么?

1 个答案:

答案 0 :(得分:2)

update不会返回dict;它只是修改接收器到位。例如,在s = A.s.update({2:2})之后,A.s被修改,sNone。你可以写一些像

这样的东西
s = dict(B.s, **{3: 3})

实现你想要的。请注意,在python 3中,这不起作用,因为关键字参数被强制为字符串。你可以写一个辅助函数:

def merge(d1, d2):
    d = dict(d1)
    d.update(d2)
    return d

然后使用s = merge(B.s, {3: 3})