Newbie question about dictionaries in classes
Sean 'Shaleh' Perry
shaleh at valinux.com
Mon Apr 23 15:47:26 EDT 2001
On 23-Apr-2001 Jacek Pliszka wrote:
> 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
> def show(self):
> print self.aaa
>
>
> 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!!
>
> What am I doing wrong?
>
by placing the dictionary outside of a function in your class you made it
global to all instances of the class. What you really want is:
def __init__(self):
self.aaa = {}
which will give each instance its own dictionary.
The global class variables are useful for things like constants or shared data
that all instances would need.
More information about the Python-list
mailing list