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]"?
testis a class attribute here, not an attribute of each instance. Don't try to "declare" members like this; you must create them in__init__.testis a class variable, not an instance variable. It is shared by all instances of your class. See, e.g., digitalocean.com/community/tutorials/….self.test, and that will shadow theExample.testclass attribute. Whereas doingself.test.append(0)merely mutates the existing object.