Common list in distinct objects'

Jake R otijim at yahoo.com
Mon Jul 15 15:41:34 EDT 2002


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

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


On Mon, 15 Jul 2002 19:22:33 GMT, otijim at yahoo.com (Jake R) wrote:

>I ran into this today.   I created a class that contains a list
>attribute.  I then add an element to the lists of each object. So each
>object should have a list with one element.
>
>However, the result I get is that, appearantly, both objects are
>sharing the same list.
>
>So, instead of two lists with one element I get one list with two
>elements.
>
>--In Addition------------------------------------------
>This only seems to occur when I use a default null list in my __init__
>method.
>
>If I change the object declaration lines to:
>	a = testList([])
>	b = testList([])
>
>Then two separate lists are created as expected.
>
>Or, if I remove the default value in the 'def __init__' and replace
>the line with:
>	self.theList = []
>
>I also get the expected two lists behavior.
>
>Can anyone help clarify this for me.
>
>
>--EXAMPLE-----------------------------------------
>
>class TestList:
>
>	def __init__(self, mylist=[]):
>		self.theList = mylist
>
>	def printList(self):
>		for x in self.theList:
>			print x
>
>	def addItemToList(self, item):
>		self.theList.append(item)
>
>
>## Program
>
>a = TestList()
>b = TestList()
>
>a.addItemToList("This is list of A")
>b.addItemToList("This is list of B")
>
>print "Print a"
>a.printList()
>print
>print "Printing b"
>b.printList()
>




More information about the Python-list mailing list