简体   繁体   中英

Inheriting static dict via dict.update()

Subclasses in my application model inherit static attributes (stored as dictionaries) from the superclass, with each subclass using update() to add fields to it's own static field. But this didn't work how I expected it to. Here's the simple version:

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

This DID work, however, when I was concatenating fields to a static list in each subclass. What am I missing?

update doesn't return a dict ; it just modifies the receiver in place. For example, after s = Asupdate({2:2}) , As is modified, and s is None . You can instead write something like

s = dict(B.s, **{3: 3})

to achieve what you want. Note that in python 3, this won't work since keyword arguments are enforced to be strings. You can write a helper function:

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

And use s = merge(Bs, {3: 3}) instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM