简体   繁体   中英

Alter superclass' variable from subclass on Python

Take this example,

class A():
    dictionary={'item1':'value1','item2':'value2'}

class B(A):

I want to be able to add a third item to the already existing dictionary of the superclass from class B. Not completely override it, just add a third value.

How can this be done?

You'd need to create a copy of the mutable dictionary into B :

class B(A):
    dictionary = A.dictionary.copy()
    dictionary['key'] = 'value'

You could do that in one step with the dict() callable:

class B(A):
    dictionary = dict(A.dictionary, key='value')

Either way B.dictionary now has 3 key-value pairs, while A has just the two:

>>> class A():
...     dictionary={'item1':'value1','item2':'value2'}
... 
>>> class B(A):
...     dictionary = dict(A.dictionary, key='value')
... 
>>> A.dictionary
{'item2': 'value2', 'item1': 'value1'}
>>> B.dictionary
{'item2': 'value2', 'item1': 'value1', 'key': 'value'}

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