Strange constructor behaviour (or not?)
Rolf Wester
rolf.wester at ilt.fraunhofer.de
Fri Apr 28 04:58:49 EDT 2006
Hi,
when defining:
class A:
def __init__(self, l=[]):
self.l = l
a = A()
a.l.append(1111)
b = A()
print a.l
I get the output
[1111]
instead of an empty list. I guess it's because the default value in the
constructor is constructed once and whenever the constructor is called
without l being specified.
My work around is:
class A:
def __init__(self, l=None):
if l == None:
self.l = []
else:
self.l = l
Is there a way to take the first definition but force the constructor to
create a new empty list every time it is called?
Thanks in advance
Rolf Wester
More information about the Python-list
mailing list