dictionary as attribute of a class...

Benjamin Kaplan benjamin.kaplan at case.edu
Wed Jan 5 10:31:25 EST 2011


On Wed, Jan 5, 2011 at 10:07 AM, tinauser <tinauser at libero.it> wrote:
> Hallo list,
> here again I have a problem whose solution might be very obvious, but
> I really cannot see it:
> I have a class having as attribute a dictionary whose keys are names
> and values are instance of another class.
> This second class has in turn as an attribute a dictionary.
> I want a function of the first class that can change value of one of
> the second class instance's dictionary.
> however I cannot do it without modifying this attribute for ALL the
> instance of the second class contained in the first class' dictionary.
> What I'm doing wrong?
>

This is one of the biggest gotchas in Python. Default arguments are
only evaluated *once*, when the function/method is declared. Not every
time the function is called. Every instance of mistClass that didn't
specify a separate cDict gets the same object as its cDict. The
solution is to use a sentinel value (either None or a single object
and use an "is" comparison) and create a new dict in the constructor
if the default argument is still the sentinel.

> class mistClass():
>    def __init__(self,name,cDict={}):
>        print 'mistClass ',name,' Init'
>        self._name=name
>        self._cDict=cDict
>

should be changed to

sentinel = object()
class mistClass :
     def __init__(self, name, cDict=sentinel) :
        print 'mistClass ',name,' Init'
        self._name=name
        if  cDict is not sentinel :
            self._cDict=cDict
        else :
            self._cDict = {}


> class mistClassContainer():
>    def __init__(self,name,dict_of_mistclass={}):
>        print 'init mistClassContainer ',name
>        self._name=name
>        self._DOM=dict_of_mistclass
>

and do the same thing with this one.



More information about the Python-list mailing list