3

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!

1
  • That error indicates something's broken about your Python installation. That's a topic for another question. Be sure to include details - which version, which OS, how you got it, etc. Commented Apr 28, 2012 at 8:21

4 Answers 4

6

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
Sign up to request clarification or add additional context in comments.

Comments

0

They aren't exactly the same, because if you do c=bla() afterwards it will only print init

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

Comments

0

Declarations such as that are for the whole class. If print was a variable assignment rather a print statement then the variable would be a class variable. This means that rather than each object of the class having its own, there is only one of the variable for the whole class.

Comments

0

They are not equivalent. Your print statement outside the init method is only called once, when he class is defined. For example, if I were to modify your main() routine to be the following:

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 executes once, when the class is being defined.

2 Comments

The print statement is executed once, when the class is defined, not when an instance of it is first created. But then you say it correctly in the last sentence...
Thanks, I've edited it to make is clearer that print would be called when class is defined and it's independent of class instantiation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.