Strange constructor behaviour (or not?)

R

Rolf Wester

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
 
D

Dave Hughes

Rolf said:
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.

Exactly right. See Python FAQ item 1.4.22
(http://www.python.org/doc/faq/general/#why-are-default-values-shared-be
tween-objects)
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?

Not as far as I know. Worth reading the above FAQ as it also contains
an interesting use of this side-effect.


Dave.

--
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top