-1

What is going on here? I would have thought b=a() would create an empty instance of the class.

class a:
    def __init__(self,l=[]):
        self.l=l

for i in range(2):
    b=a()
    b.l.append(1)
    print b.l

results in:

[1]
[1, 1]
Stefan
  • 146
  • 4

3 Answers3

2

When you have list as default argument, a new list is created only once, when the function is defined, then the same list is used in each call. To "solve" this, you can do:

class a:
    def __init__(self,l=None):
        if l is None:
            self.l = []
        ...
Maroun
  • 94,125
  • 30
  • 188
  • 241
0

You can read a nice explanation of what's going on here : http://effbot.org/zone/default-values.htm

>>> def function(data=[]):
...     data.append(1)
...     return data
...
>>> function()
[1]
>>> function()
[1, 1]
>>> function()
[1, 1, 1]

And the proper way to do it in your case:

class a:
    def __init__(self, l=None):
        if l is None:
            l = []
        self.l=l

for i in range(2):
    b=a()
    b.l.append(1)
    print b.l
Maxime Chéramy
  • 17,761
  • 8
  • 54
  • 75
0

When you do l=[] in function arguments list - you declare static list (list object will be created only once), so each time you append new element to the same list object.

You might need something like this to create new list object for each new A object:

class A:
    def __init__(self, l=None):
        self.l = l or []

for i in range(2):
    b=A()
    b.l.append(1)
    print b.l
Stanislav
  • 826
  • 11
  • 17