列为python类的成员,为什么它的内容在该类的所有实例之间共享? [英] List as a member of a python class, why is its contents being shared across all instances of the class?

查看:65
本文介绍了列为python类的成员,为什么它的内容在该类的所有实例之间共享?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经定义了一个类Listener,并创建了一个Listener对象的字典.每个侦听器都有一个id来标识它们,还有一个侦听的artists列表artists = [].将某些内容添加到artists列表会将其添加到Listener类的所有实例,而不是所引用的实例.这是我的问题.

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.

Listener类的定义如下:

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)

输出:

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)调用将导致输出

My expected output is that the final addArtist("Ace of Base", 5) call would result in the output

1
pre:  []
post:  ['Ace of Base']

这是我不了解的Python的精妙之处吗?为什么这是输出,我如何才能获得所需的输出呢?谢谢!

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!

推荐答案

您不希望在类中声明成员,而只是在__init__方法中进行设置:

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

如果您有类似的课程

class A:
  x=5

然后x是该类的成员,而不是该类的实例的成员.这可能会造成混淆,因为python允许您通过实例访问类成员:

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

但是实际上发生的是,您已经将一个新的x放入a1实例中,它将被打印,而不是仍具有其原始值的类成员:

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]

这篇关于列为python类的成员,为什么它的内容在该类的所有实例之间共享?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆