列表作为 python 类的成员,为什么它的内容在该类的所有实例之间共享?

2024-04-23

我定义了一个类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的微妙之处吗?为什么这是输出以及如何获得所需的输出?谢谢!


您不希望在类内部声明成员,而只需在__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

如果你有这样的课程

class A:
  x=5

那么 x 是该类的成员,而不是该类的实例的成员。这可能会令人困惑,因为 python 允许您通过实例访问类成员:

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

但您也可以通过类本身访问它:

>>> print A.x
5

甚至看起来这工作正常:

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

但实际发生的情况是,您将一个新的 x 放入 a1 实例中,它将代替类成员打印,该成员仍然具有其原始值:

>>> print A.x
5

只有当您有可以更改的内容(例如列表)时,您才会开始看到差异:

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]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

列表作为 python 类的成员,为什么它的内容在该类的所有实例之间共享? 的相关文章

随机推荐