Common list in distinct objects'

John Hunter jdhunter at nitace.bsd.uchicago.edu
Mon Jul 15 16:17:22 EDT 2002


>>>>> "Jake" == Jake R <otijim at yahoo.com> writes:

    Jake> Now that I think about it some more I seem to remember
    Jake> reading somewhere in the tutorial that class definition is
    Jake> only processed once and being so means that the default list
    Jake> (myList=[]) in my __init__ is only created once and thus any
    Jake> objects created all point to the same list unless I create a
    Jake> new list (ie pass one in or have the __init__ function do it
    Jake> when its called)

    Jake> Does that sound right?  Still....I don't think thats what
    Jake> way it ought to behave.

In python, all arguments are passed by reference, which means that the
when you pass a list to a function, the copy of the list inside and
outside the list are the same.  Consider this code:

def somefunc(x):
	x.append('In func')

y = []
y.append('Before func')
somefunc(y)
y.append('After func')
print y

The contents of y are ['Before func', 'In func', 'After func'] because
it is the same list.

Now in your case, when a and b are both initialized use the default
value of mylist=[], they both refer to the same list '[]' and so
appending to one is the same as appending to the other.

Likewise, in the following code, both a and b refer to the same list

# Compare the following two cases
# a and b have the same lists
x = [s]
a = TestList(x)
b = TestList(x)


But in this case they do not
a = TestList([s])
b = TestList([s])

Note the difference between equality (with the '==' operator) and
identity (with the 'is' operator).  In python, 2 lists are equal if
all the elements compare equal, are are identical if they refer to the
same list

>>> s = 'Hi'
>>> x = [s]
>>> y = [s]
>>> x==y
1
>>> x is y
0

>>> z = x
>>> x==z
1
>>> x is z
1

But note that 
>>> [] is []
0

So two copies of [] are not identical (though they are equal). 

When you create a default arg to a function, python only makes one
instance of it, so all functions share the same default object.  Thus
in the case of your init function, two instances a and b do not refer
to two copies of the empty list, but to the same copy of the empty
list.  See

  http://www.python.org/cgi-bin/faqw.py?req=all#6.25

Cheers,
John Hunter



More information about the Python-list mailing list