I have defined a class Listener and created a dictionary of Listener objects. Each listener has an id to identify them, and a list of artists they listen to, artists = []. Adding something to the artists list adds it for all instances of the Listener class, rather than the referred instance. This is my problem.
The Listener class is defined as follows:
class Listener:
id = ""
artists = []
def __init__(self, id):
self.id = id
def addArtist(self, artist, plays):
print self.id # debugging...
print "pre: ", self.artists
self.artists.append(artist)
print "post: ", self.artists
Here is my debugging test code:
def debug():
listeners = {}
listeners["0"] = Listener("0")
listeners["1"] = Listener("1")
listeners["0"].addArtist("The Beatles", 10)
listeners["0"].addArtist("Lady Gaga", 4)
listeners["1"].addArtist("Ace of Base", 5)
And the output:
0
pre: []
post: ['The Beatles']
0
pre: ['The Beatles']
post: ['The Beatles', 'Lady Gaga']
1
pre: ['The Beatles', 'Lady Gaga']
post: ['The Beatles', 'Lady Gaga', 'Ace of Base']
My expected output is that the final addArtist("Ace of Base", 5) call would result in the output
1
pre: []
post: ['Ace of Base']
Is this a subtlety of Python I’m not understanding? Why is this the output and how can I get the desired output instead? Thanks!
You don’t want the members declared inside the class, but just set in the
__init__method:If you have a class like
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:
But you can also access it through the class itself:
It would even appear that this works properly:
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:
You only start to see a difference when you have something that can be changed, like a list: