new class-instance is not getting initialized

Erik Max Francis max at alcyone.com
Sat Mar 15 19:18:16 EST 2003


Axel Straschil wrote:

>         def __init__(self, flags=[]):
	...
>         def __init__(self, props={}):
	...
>         def __init__(self, tag, flags=[], props={}, Class=None):
	...
>         def __init__(self, tag, content=None, flags=[], props={},
> Class=None):
	...
>         def __init__(self, type=None, name=None, value=None,
> size=None, flags=[],

The problem is here.  In Python, default arguments are evaluated and
stowed away once, at definition time.  When those objects are mutable
(e.g., lists and dictionaries), that means that the mutable object is
shared by all callers:

>>> def f(x, l=[]):
...  l.append(x)
...  print l
... 
>>> f(1)
[1]
>>> f(2)
[1, 2]
>>> f(3)
[1, 2, 3]

Usually this isn't what you want (as in this case), so you should
protect the mutable objects with something like:

>>> def g(x, l=None):
...  if l is None:
...   l = [] # this way it'll be a unique object every time
...  l.append(x)
...  print l
... 
>>> g(1)
[1]
>>> g(2)
[2]
>>> g(3)
[3]


-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ But since when can wounded eyes see / If we weren't who we were
\__/ Joi
    Crank Dot Net / http://www.crank.net/
 Cranks, crackpots, kooks, & loons on the Net.




More information about the Python-list mailing list