Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declarations within python class equivalent to _init_?

Tags:

python

I was wondering if the declarations put at the top of the python class are equivalent to statements in __init__? For example

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() )

The output is:

not init
init
whatever

As a sidenote, right now I also get:

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's support team for more information.

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

like image 797
Cenoc Avatar asked Feb 16 '26 16:02

Cenoc


1 Answers

No, it's not equivalent. The statement print 'not init' is run while the class bla is being defined, even before you instantiate an object of type bla.

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

>>> b = bla()
init
like image 159
Mark Byers Avatar answered Feb 19 '26 06:02

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!