List as a member of a python class, why is its contents being shared across all instances of the class?

You don’t want the members declared inside the class, but just set in the __init__ method:

class Listener:
    def __init__(self, id):
        self.id = id
        self.artists = []

    def addArtist(self, artist, plays):
        print self.id # debugging...
        print "pre: ", self.artists
        self.artists.append(artist)
        print "post: ", self.artists

If you have a class like

class A:
  x=5

Then x is a member of the class and not a member of instances of that class. This can be confusing, since python lets you access class members through the instance:

>>> a=A()
>>> print a.x
5

But you can also access it through the class itself:

>>> print A.x
5

It would even appear that this works properly:

>>> a1=A()
>>> a2=A()
>>> a1.x=6
>>> print a1.x
6
>>> print a2.x
5

but what has actually happened is that you’ve put a new x into the a1 instance, which will be printed instead of the class member, which still has its original value:

>>> print A.x
5

You only start to see a difference when you have something that can be changed, like a list:

class A:
  l=[]

>>> a1=A()
>>> print a1.l
[]
>>> a2=A()
>>> print a2.l
[]
>>> a1.l.append(5)
>>> print a1.l
[5]
>>> print a2.l
[5]
>>> print A.l
[5]

Leave a Comment