class MyClass(object):
myVar = None
myArr = ['default']
m = MyClass()
m.myVar = 28
m.myArr.append('foo')
print 'CLASS\t\tmyVar: %s\tmyArr: %s' % (MyClass.myVar, MyClass.myArr)
print 'INSTANCE\tmyVar: %s\tmyArr: %s' % (m.myVar, m.myArr)What is the output?
CLASS myVar: None myArr: ['default', 'foo'] INSTANCE myVar: 28 myArr: ['default', 'foo']
Why?
m.myVar = 28 creates a new instance attribute called ‘myVar’, but m.myArr.append('foo') modifies a class attribute. This was confusing the first time I ran into it, and luckily I wasn’t the only one.