A default in the __init__ is like a class variable?

Peter peter at engcorp.com
Sun Mar 30 09:32:06 EST 2003


Jens Gelhaar wrote:
> 
> Is this a feature?
> 
> >>> class test:
> ...   def __init__(self,t=[]):
> ...       self.t=t
> 
> I know why both t has the same list, but I would not expect this. Each
> instance should have it's own list.

As Just said, plus this fix to your "buggy" code: :-)

>>> class test:
...   def __init__(self,t=None):
...       if t is None: t = []
...       self.t=t

The rule is "Don't use mutables for default arguments unless you
want the 'unexpected' behaviour."  It's a fairly simple rule...

-Peter




More information about the Python-list mailing list