Inheriting dictionary attributes and manipulate them in subclasses
Diez B. Roggisch
deets at nospam.web.de
Fri Apr 17 11:48:55 EDT 2009
Dominik Ruf wrote:
> 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?
No, because you are creating *classvariables* when declaring things like
this:
class Foo(object):
bar = {}
If these are mutable, changing them will change them for *all* instances.
OTOH, when assigning to an instance, this will create an
*instance*-variable. Which is what
self.some_name = some_value
does.
Diez
More information about the Python-list
mailing list