Reputation: 11662
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!
Upvotes: 3
Views: 783
Reputation: 3333
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.
Upvotes: 0
Reputation: 7271
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.
Upvotes: 0
Reputation: 11915
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
.
Upvotes: 0
Reputation: 837986
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
Upvotes: 6