python bug?

Christopher T King squirrel at WPI.EDU
Mon Jul 26 15:39:31 CEST 2004


On Mon, 26 Jul 2004, Anthony Petropoulos wrote:

> When running this simple code:
> -------
> class Dada:
>         a = []
>         def __init__(self, arg):
>                 self.a.append(arg)
> 
> d1 = Dada("pro")
> d2 = Dada("hoho")
> 
> print d1.a, d2.a
> ------------
> I get the output ['pro', 'hoho'] ['pro', 'hoho'], instead of what I
> expected: ['pro'] ['hoho'].

In your code, 'a' is initialized at the class level.  This means that it 
is only initialized once, when the class is first created.  Each time you 
instantiate a new object, it's using the same list bound to a.  To do what 
you want, you need to initialize 'a' for each object, rather than the 
class as a whole:

 class Dada:
         def __init__(self, arg):
                 self.a = []
                 self.a.append(arg)

 d1 = Dada("pro")
 d2 = Dada("hoho")
 
 print d1.a, d2.a	# -> ['pro'] ['hoho']




More information about the Python-list mailing list