Python pregenerates class properties

This article is a reference because this cost me about an hour to debug:

class test(object):
foo = []

a = test()
b = test()
a.foo.append("bar")
print b.foo
#['bar']

When you define the class (test, in this case), any class properties will be instanciated on class-definition and not on object instanciation. Therefore, when you create multiple copies of a class, they will have the same actual object as class properties. You should instanciate those attributes in the init-method.

For this reason, the following code will generate output, even though it looks like it probably shouldn’t, because not a single object was created:
def f():
print "foo"

class test(object):
foo = [f()]

This will obviously not concern you, if you are – as you should – using immutable objects.

Kommentar verfassen