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]"?

6
  • 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__. Commented Aug 19, 2017 at 12:59
  • test is a class variable, not an instance variable. It is shared by all instances of your class. See, e.g., digitalocean.com/community/tutorials/…. Commented Aug 19, 2017 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. Commented Aug 19, 2017 at 13:14
  • @PM2Ring Okay, now I understand. Thank's! Commented Aug 19, 2017 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. Commented Aug 19, 2017 at 13:17

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.