dictionary as attribute of a class...

tinauser tinauser at libero.it
Wed Jan 5 10:44:16 EST 2011


On Jan 5, 4:34 pm, Peter Otten <__pete... at web.de> wrote:
> tinauser 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?
>
> > the code:
>
> > ###############
> > ###can i change a dictionary attribute of an instantated object
> > without affectin all the instances of that object?
>
> > class mistClass():
> >     def __init__(self,name,cDict={}):
>
> When you don't provide a cDict argument the default is used which is the
> same for every instance. Change the above to
>
> def __init__(self, name, cDict=None):
>     if cDict is None:
>         cDict = {}
>
> > class mistClassContainer():
> >     def __init__(self,name,dict_of_mistclass={}):
>
> Same here.
>
> >     def setName(self,n):
> >         self._name=n
>
> >     def getName(self):
> >         return self._name
>
> Python has properties, so you don't need this just-in-case getter/setter
> nonsense.
>
> >         for k,v in zip(listK,listV):
> >             self._cDict[k]=v
>
> Make that
>
> self._cDict.update(zip(listK, listV))
>
> By the way, not everyone loves Hungarian notation...

Thanks both for the reply, I'll take some time to digest so to avoid
further error in the future.Thanks again.



More information about the Python-list mailing list