470,600 Members | 1,527 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,600 developers. It's quick & easy.

Strange constructor behaviour (or not?)

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
Apr 28 '06 #1
1 863
Rolf Wester wrote:
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/genera...lues-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.

--

Apr 28 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

24 posts views Thread by brian.bird | last post: by
10 posts views Thread by Sony Antony | last post: by
5 posts views Thread by Levent | last post: by
19 posts views Thread by Andrew J. Marshall | last post: by
9 posts views Thread by hfinster | last post: by
74 posts views Thread by Zytan | last post: by
8 posts views Thread by Dox33 | last post: by
17 posts views Thread by Ioannis Vranos | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.