修改 class 的一个实例会影响另一个实例

Modifying one instance of class affects another

看看这个简单的片段

from SwitchState import SwitchState

s1 = SwitchState()
s1.add(12345, True)

s2 = SwitchState()

print(s2.get_all())

结果是:[(12345, True)] !

我正在将项目添加到 s1,但也在 s2 中得到它!我做错了什么?

SwitchState.py

import struct


class SwitchState(object):

    _states = []

    def add(self, timestamp, state):
        self._states.append((timestamp, state))

    def get_all(self):
        return self._states

它们都具有相同的 _states,因为它是 class 属性。

class ...
  def __init__(self):
    self._states = []