Neka
Neka

Reputation: 1664

Modifying one instance of class affects another

Look at this simple snippet

from SwitchState import SwitchState

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

s2 = SwitchState()

print(s2.get_all())

Result is: [(12345, True)] !

I'm adding the item to s1 but got it in s2 too! What im doing wrong?

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

Upvotes: 0

Views: 23

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

They both have the same _states, since it's a class attribute.

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

Upvotes: 1

Related Questions