It's all rather straightforward. When a module is loaded, code is run from the top to the bottom. Global variables will thus be instantiated as they appear in the module code. When a function is called, the code in it runs from top to bottom.
Decorators are somewhat of an exception in that they are called after the function they are decorating has been defined, in bottom to top order. So if you have:
@hits
@dies
@rofls
def watcher(): pass
it's the same as:
def watcher(): pass
watcher = hits(dies(rofls(watcher)))
This makes sense if you think of each decorator wrapping everything below it.
When an object is created, first __new__
is called, then __init__
. super()
is called if you happen to have a call to it somewhere, much like anything else... 'constructor variables' are just initialized whenever you happen to have variable assignment in an __init__
.
EDIT: To look at your example:
class A(superA):
class_var = 1234
def __init__(self):
superA.__init__(self)
another_var = 5678
@random_decorator
def method(self):
# do stuff
I will instead teach you how to fish.
def random_decorator(f):
print "random_decorator called"
return f
def init_var(varname, val):
print '%s being initialized' % (varname,)
return val
class superA(object):
def __new__(cls):
print 'superA.__new__ called'
return super(superA, cls).__new__(cls)
def __init__(self):
print "superA.__init__ called"
class A(superA):
class_var = init_var('class_var', 1234)
def __new__(cls):
print 'A.__new__ called'
return super(A, cls).__new__(cls)
def __init__(self):
print 'A.__init__ called'
superA.__init__(self)
another_var = init_var('another_var', 5678)
@random_decorator
def method(self):
print 'method called'
# do stuff
class_var2 = init_var('class_var2', 9012)
A().method()
See what order the print statements come out in.