Search code examples
pythonscopemutable

Why do new instances of a class share members with other instances?


class Ball:
  a = []
  def __init__(self):
    pass

  def add(self,thing):
    self.a.append(thing)

  def size(self):
    print len(self.a)

for i in range(3):
  foo = Ball()
  foo.add(1)
  foo.add(2)
  foo.size()

I would expect a return of :

2
2
2

But I get :

2
4
6

Why is this? I've found that by doing a=[] in the init, I can route around this behavior, but I'm less than clear why.


Solution

  • doh

    I just figured out why.

    In the above case, the a is a class attribute, not a data attribute - those are shared by all Balls(). Commenting out the a=[] and placing it into the init block means that it's a data attribute instead. (And, I couldn't access it then with foo.a, which I shouldn't do anyhow.) It seems like the class attributes act like static attributes of the class, they're shared by all instances.

    Whoa.

    One question though : CodeCompletion sucks like this. In the foo class, I can't do self.(variable), because it's not being defined automatically - it's being defined by a function. Can I define a class variable and replace it with a data variable?