gdaramouskas
gdaramouskas

Reputation: 3747

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?

Upvotes: 0

Views: 43

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121744

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'}

Upvotes: 2

Related Questions