problem with nested dictionaries

Brian Quinlan brian at sweetapp.com
Thu Oct 3 06:42:19 CEST 2002


> However, when I print out the list, the objects which I inserted under
> C2-object '3', appear to have been inserted in the other objects as
> well.
> 
> What am I doing wrong (just started with python)
> 
> I am using Python 2.2
> 
> 
> #<< begin snip
> 
> class C1:
>     class_C1_name = ""
>     def __init__(self, n):
>         self.class_C1_name = n
> 
> class C2:
>     class_C2_name = ""
>     a_list     = {}
>     def __init__(self, n):
>         self.class_C2_name = n
> 

The problem is that a_list is scoped at the class level, not the
instance level i.e. every C2 will share the same "a_list".

You can fix that:

class C2:
	class_C2_name = ""
	def __init__(self, n):
	   self.a_list = {}
         self.class_C2_name = n
 

Cheers,
Brian





More information about the Python-list mailing list