Strange constructor behaviour (or not?)

Dave Hughes dave at waveform.plus.com
Fri Apr 28 05:14:59 EDT 2006


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/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.

-- 




More information about the Python-list mailing list