A default in the __init__ is like a class variable?

Alex Martelli aleax at aleax.it
Mon Mar 31 04:34:56 EST 2003


Jens Gelhaar wrote:

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

That's not what you've coded!  When you code:
    self.t = t
you are NOT ensuring that each instance will have their own list -- on
the contrary, you're specifically asking for multiple instances to be
able to share one list.  Python does no copies unless you explicitly
ASK for copies!  It's not just a matter of the default value, mind:

x = range(3)
a = test(x)
b = test(x)

here a.t is x, b.t is x, a.t is b.t.  You coded it that way!!!  So ANY
mutation done through any of these references to the one and only
underlying object, e.g. a.t.append('uh?'), will OF COURSE be visible
through all references equally -- they're all references to the SAME
object, so how could it possibly be otherwise?!

Just change the body of __init__ to:

    self.t = list(t)

and NOW your code is expressing EXACTLY what your later words said --
each instance WILL have its own attribute, AND that attribute will MOST
definitely be a list, whatever type argument t is (you'll get an
exception if t is of such a type that no list can be built from it).

If you really mean it when you say "each instance should have its
own list", then CODE it that way -- it's as simple as this.  If you
mean something slightly different, then code it in condign slightly
different ways.  Again, it IS as simple as this.  Python does what
you TELL it to do -- it does NOT try to read your mind and impose
what somebody thinks "should" happen but is different than _what
you have ACTUALLY coded_.  This crucial language design choice is
part of what makes Python simple AND powerful at the same time.


Alex





More information about the Python-list mailing list