Python class declarations equivalent to _init_?

I was wondering if the declarations placed at the beginning of the python class are equivalent to the statements in __init__? for instance

import sys

class bla():
    print 'not init'
    def __init__(self):
        print 'init'
    def whatever(self):
        print 'whatever'

def main():
    b=bla()
    b.whatever()
    return 0

if __name__ == '__main__':
    sys.exit( main() )

Conclusion:

not init
init
whatever

As a support, right now I am also getting:

Fatal Python error: PyImport_GetModuleDict: no module dictionary!

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application support team for more information.

Any ideas on why this is? Thank you in advance!

+3
source share
4 answers

No, this is not equivalent. The statement print 'not init'runs while the class blais defined, even before you create the type object bla.

>>> class bla():
...    print 'not init'
...    def __init__(self):
...        print 'init'
not init

>>> b = bla()
init
+6
source

They are not quite the same, because if you do c=bla(), it will only printinit

Also, if you reduce main()to return 0, it still prints not init.

0
source

, . , , . , , , .

0

They are not equivalent. Your print statement outside the init method is called only once when it is defined by the class. For example, if I have to change your main () procedure as follows:

def main():
    b=bla()
    b.whatever()
    c = bla()
    c.whatever()
    return 0

I get the following output:

not init
init
whatever
init
whatever

The not init print statement is executed once when the class is defined.

0
source

All Articles