0

I came across some rather strange behavior.

class Example:
    test = []

    def __init__(self):
        print(self.test)
        self.test.append(0)


ex1 = Example()
ex2 = Example()
ex3 = Example()

I'd expect this to output [] every time, however, I get:

[]
[0]
[0, 0]

What is this wizardry? Could you help me understand?
Thank, you!

Edit: Hey, thank you for the quick answers.

Just to clarify, if "test" is static then why do I not notice this behavior when I replace "self.test.append(0)" with "self.test = [0]"?

Alex P.
  • 488
  • 5
  • 12
  • `test` is a *class* attribute here, not an attribute of each *instance*. Don't try to "declare" members like this; you must create them in `__init__`. – Jonathon Reinhart Aug 19 '17 at 12:59
  • `test` is a class variable, not an instance variable. It is shared by all instances of your class. See, e.g., https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3. – larsks Aug 19 '17 at 12:59
  • 1
    «why do I not notice this behavior when I replace "self.test.append(0)" with "self.test = [0]"?» Because that binds a new object to the instance attribute `self.test`, and that will shadow the `Example.test` class attribute. Whereas doing `self.test.append(0)` merely mutates the existing object. – PM 2Ring Aug 19 '17 at 13:14
  • @PM2Ring Okay, now I understand. Thank's! – Alex P. Aug 19 '17 at 13:15
  • BTW, please try to avoid modifying questions after they've already received valid answers. If you need additional clarification about an answer, do it in the comments of that answer, or ask a fresh question (possibly linking to the original question). Otherwise, you risk invalidating those answers & the answerers may not notice. – PM 2Ring Aug 19 '17 at 13:17
  • @PM2Ring Ok, good to know. – Alex P. Aug 19 '17 at 13:19

2 Answers2

2

test is a static class attribute, which you are continually updating with values. Python is different from some other languages in this way. To make it an object attribute, use self.test = [] in your constructor.

damd
  • 6,116
  • 7
  • 48
  • 77
1

test there is a class-level static variable, which is shared between the instances of the class.

You'll want to initialize test within the __init__ method.

class Example:

    def __init__(self):
        self.test = []
        print(self.test)
        self.test.append(0)
AKX
  • 152,115
  • 15
  • 115
  • 172