bizarre Recursive/class interaction

Steven Taschuk staschuk at telusplanet.net
Tue Mar 11 14:19:43 EST 2003


Quoth Bob Roberts:
> > This is a common gotcha.  The default value is evaluated only once
> > (not each time the function is called). 
> 
> Does this mean that the variable data in 
> def __init__(self, data = []):
> behaves like a static variable in C/C++?

Not 'data', which is a formal parameter; that name is bound anew
on each call to __init__.  But the empty list which is its default
value, yes, that behaves like a static variable in C.

> > Something like this is probably better:
> > 
> >     class MyClass(UserList.UserList):
> >         def __init__(self, data=None):
> >             UserList.UserList.__init__(self, data)
> >             if self.data:
> >                 print self.data
> > 
> Why does this work (and it does seem to)?  If each instance only usese
> one "data", then why would it matter if the default value is [] or
> None?

That I've used None is almost incidental.  The important point is
that the initialization of self.data has been delegated to
UserList.__init__, which correctly creates a new list.

If you were writing it yourself, you could do something like this:

	def __init__(self, data=None):
		if data is None:
			self.data = []
		else:
			self.data = self.data[:]

Here the empty list is created in the body of the function, and so
it's a new empty list every time the function is called, unlike a
default argument, which is the same object every time the function
is called.

-- 
Steven Taschuk             "The world will end if you get this wrong."
staschuk at telusplanet.net    (Brian Kernighan and Lorrinda Cherry,
                            "Typesetting Mathematics -- User's Guide")





More information about the Python-list mailing list