Lists in classes

kyosohma at gmail.com kyosohma at gmail.com
Thu Jul 12 11:33:20 EDT 2007


On Jul 12, 10:23 am, Jeremy  Lynch <jeremy.ly... at gmail.com> wrote:
> Hello,
>
> Learning python from a c++ background. Very confused about this:
>
> ============
> class jeremy:
>         list=[]
>                 def additem(self):
>                 self.list.append("hi")
>                 return
>
> temp = jeremy()
> temp.additem()
> temp.additem()
> print temp.list
>
> temp2 = jeremy()
> print temp2.list
> ==============
> The output gives:
> ['hi','hi']
> ['hi','hi']
>
> Why does adding items to one instance produce items in a separate
> instance? Doesn't each instance of jeremy have its' own "list"?
>
> Many thanks for clearing up this newbie confusion.
>
> Jeremy.

The reason it works like that is that your variable "list" isn't an
instance variable per se. Instead, you should have it like this:

<code>

class jeremy:
    def __init__(self):
        self.lst=[]
    def additem(self):
	self.lst.append("hi")
	return

</code>

Now it works as expected. It's some kind of scope issue, but I can't
explain it adequately.

Mike




More information about the Python-list mailing list