Inheriting dictionary attributes and manipulate them in subclasses

Dominik Ruf dominikruf at googlemail.com
Fri Apr 17 11:39:04 EDT 2009


Hi,

I just stumbled upon the following behaviour.
>>> class base():
...   dic = {'1':'1', '2':'2'}
...
>>> class child1(base):
...   def __init__(self):
...     self.dic.update({'1':'2'})
...
>>> class child2(base):
...   pass
...
>>> c1 = child1()
>>> c2 = child2()
>>>
>>> print c1.dic
{'1': '2', '2': '2'}
>>> print c2.dic
{'1': '2', '2': '2'}

This is not what I have excepted.
Although I know the solution to get what I want...
>>> class base():
...   def __init__(self):
...     self.dic = {'1':'1', '2':'2'}
...
>>> class child1(base):
...   def __init__(self):
...     base.__init__(self)
...     self.dic.update({'1':'2'})
...
>>> class child2(base):
...   pass
...
>>> c1 = child1()
>>> c2 = child2()
>>>
>>> print c1.dic
{'1': '2', '2': '2'}
>>> print c2.dic
{'1': '1', '2': '2'}

... I wonder if there is a special reason for the behaviour in the
first example.
Shouldn't the first example behave like the second?

cheers
Dominik



More information about the Python-list mailing list