Newbie question about dictionaries in classes

Alex Martelli aleaxit at yahoo.com
Mon Apr 23 16:47:10 EDT 2001


"Jacek Pliszka" <pliszka at fuw.edu.pl> wrote in message
news:Pine.LNX.4.30.0104232122310.23315-100000 at ift4.fuw.edu.pl...
> Hi!
>
> I just started to learn Python and I got stuck with the following
> problem:
>
> class myclass:
>     aaa={}
>     def add(self,u):
>         (self.aaa)[u]=1
    [snip]
> then I get the result that aaa in both ula and ola
> is identical!!! I thought that aaa will be different for
> ula and ola!!

You're binding aaa in the class body, so it's an attribute of
the whole class; every instance shares it.

> What am I doing wrong?

Nothing, it's a fine idiom -- all instances can share state.

If you DON'T want to share state, just ensure each
instance gets its own, e.g. add a method for instance
initialization instead of the class-level aaa binding:

class myclass:
    def __init__(self):
        self.aaa={}
    def add(self,u):
        (self.aaa)[u]=1

etc.


Alex






More information about the Python-list mailing list