The following code will result in the print statement being executed
class C1(object):
print 'I am some code executing in C1'
def method1(self):
print 'I am method1'
def method2(self):
print 'I am method2'
pass
I am surprised by this as I would have thought it would only execute if the class was instantiated, can anyone explain the thinking behind this?
I guess you mean that it prints ‘I am some code executing in C1’?
It’s printed when the class object is created, and in this case that happens when you load the file it’s declared in. This is also the place where you put class variables (which can be used as Python’s equivalent of static variables in other languages).
If you want to have code that is executed upon creating instance, put it in
__init__().Official Python documentation on the subject: http://docs.python.org/tutorial/classes.html#class-objects