Lists in classes

Bart Ogryczak B.Ogryczak at gmail.com
Thu Jul 12 11:30:54 EDT 2007


On 12 jul, 17:23, 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"?

You've defined list (very bad choice for a name), as a class variable.
To declare instance variable you should have written:
class jeremy:








More information about the Python-list mailing list