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

后端 未结 2 1875
深忆病人
深忆病人 2021-02-01 04:35

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

2条回答
  •  借酒劲吻你
    2021-02-01 04:54

    Is this a subtlety of Python I'm not understanding?

    It's not subtle, it's quite simple; unlike in other languages which confuse the issue, in Python everything you declare inside the class belongs to the class. This is natural, since classes are objects (like everything else), and thus a perfectly valid place to attach things. Thus, all those methods belong to the class (instead of being somehow magically copied to each instance), and so do the data attributes.

    Each listener has an id to identify them

    Yes, because you attach one to each instance in the __init__. This has nothing to do with the id that belongs to the class - except that when you look up id via an instance, the instance's own id will be found, hiding the one belonging to the class.

    and a list of artists they listen to, artists = []

    When you look up artists via the class, however, the class' artists will be found, because the instance doesn't have one.

    Adding something to the artists list adds it for all instances of the Listener class

    No; it's added to the class itself, which is where things are looked for when they aren't found in the instance.

    Keep in mind that if you made a direct assignment like self.artists = [] on an instance later, that instance would get its own list hiding the class' list. Other instances would not, because that code didn't get run on the other instances.

提交回复
热议问题