0

In this answer it's said that

all of the code that is at indentation level 0 gets executed. Functions and classes that are defined are, well, defined, but none of their code gets run.

However, if I have the following foo.py:

print("Line 1")


class HelloWorld:
    print(__name__)
    if True:
        print("Hello, World!")


class Hello2:
    print(__name__)
    print("Hello 2")


def functionA():
    print("Running code in function")

I would expect that only "Line 1" is printed, but when I run it, I get

Line 1
__main__
Hello, World!
__main__
Hello 2

Why is the code in the classes being executed?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
antonro
  • 449
  • 2
  • 4
  • 10

2 Answers2

1

The other answer you referenced is correct, but "all the code at indentation 0 is executed" does not mean "none of the code at other indentation levels is executed". In this case, processing the class statements (which are at indentation 0) requires executing the indented code they contain.

Obviously, this line is executed and does what you expect:

print("Line 1")

This block at the end is executed, defining a function. The function never gets called, so this print statement is not actually executed

def functionA():
    print("Running code in function")

The two class definitions are also executed. Executing a class definition creates a class object. In order to initialize that class object, the code within the class definition is executed. Most often, this would consist of def statements to define functions within the class. Just like the free-standing def example, the def statement would be executed, creating a function object, but the function would not be called.

In your case, you have code in the class definitions that does stuff other than define functions. This allows you to have code that sets initial state for the class object. These are executed as part of processing the class statement, and therefore you see their side effects at that point.

Dave Costa
  • 47,262
  • 8
  • 56
  • 72
0

because python needs to "build" the classes when executing the file, and that part of the code is part of the "build" process.

the class is only built once in the lifetime of your program. for example if you add at the end of your script

instanceOne = HelloWorld()
instanceTwo = Hello2()

you will see that none of the print statements will be executed again.

fahyik yong
  • 141
  • 6