Logiciel Libre

September 7, 2007

Python Gotcha: Class vs. Attribute data

Filed under: Default — Tags: — adam @ 7:00 am
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.

No Comments »

No comments yet.

RSS feed for comments on this post.

Leave a comment

Powered by WordPress