2

I was wondering why when I run a python script like the one showed below, the interpreter prints the print that is inside the class even if the class has not been instantiated.

AFAIK, python first reads what is global, then it goes to the main method and from there it can call other objects.

print "BRAVO 1"

class Foo():

    print "BRAVO 2"

    def __init__(self):
        print "BRAVO 3"

print "BRAVO 4"

if __name__ == "__main__":
    print "BRAVO MAIN"

prints

BRAVO 1
BRAVO 2
BRAVO 4
BRAVO MAIN
NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104

1 Answers1

3

Python will create the class object when you run the code, and as such it will print "BRAVO 2" even though you haven't created any instances of Foo.

If you were to create an instance of Foo with foo = Foo() then it would also print "BRAVO 3", as that is inside the __init__ function which is called upon initialisation.

Ffisegydd
  • 51,807
  • 15
  • 147
  • 125