我定义了一个类Listener
并创建了一本字典Listener
对象。每个听众都有一个id
来识别它们,以及一个列表artists
他们听,artists = []
。添加一些东西到artists
列表将其添加到的所有实例Listener
类,而不是引用的实例。这是我的问题。
Listener类定义如下:
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
这是我的调试测试代码:
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)
和输出:
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']
我的预期输出是最终的addArtist("Ace of Base", 5)
调用会产生输出
1
pre: []
post: ['Ace of Base']
这是我不理解的Python的微妙之处吗?为什么这是输出以及如何获得所需的输出?谢谢!