0
class a:
    b = []

c = a()
d = a()
print(c.b, d.b) # output:   [] []
c.b.append(1)
print(c.b, d.b) # expected: [1] []
                # output:   [1] [1]

What exactly is happening here? I'm trying to develop an application, and as you may guess, this thing is making it kinda difficult.

I'd like to know what Python thinks it's doing here, and what I should do differently.

If relevant, my Python version is

Python 3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)] on win32

PurkkaKoodari
  • 6,703
  • 6
  • 37
  • 58

1 Answers1

2

The b variable is assigned at the top level the class, so it is a class variable. That means that you always see the same list object regardless of which instance you access it through (or if you access it through the class directly, as a.b).

If you want a separate list in each instance, create the variable with an assignment to an attribute of self in an __init__ method:

class a:
    def __init__(self):
        self.b = []
Blckknght
  • 100,903
  • 11
  • 120
  • 169