bizarre Recursive/class interaction
Bob Roberts
bobnotbob at byu.edu
Tue Mar 11 09:44:43 EST 2003
>
> 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++?
>
> In your code, each instance of MyClass uses the same list as
> self.data, so changes to one instance will be reflected in the
> others. Also -- it will be reflected in the default value for new
> instances. Hence the assertion failure on the second list you
> create.
>
> 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?
More information about the Python-list
mailing list