-1

Consider following code

class A():
    print("hello")
    value = 44
    def __init__(self):
        print("init")

if __name__ == "__main__":
    pass

Output:

>>> 
hello
>>> 

The variable or expression... are inside class but outside any methods. By running this script I would expect that nothing happens because I didn't instantiate anything. Why is the interpreter executing it?

Module_art
  • 999
  • 2
  • 9
  • 26
  • 1
    Note that `if __name__ == "__main__": pass` does nothing – wjandrea Jun 11 '20 at 18:56
  • Does this answer your question? [Order of execution with python class](https://stackoverflow.com/questions/55793567/order-of-execution-with-python-class) – wjandrea Jun 11 '20 at 19:14
  • or [Why does a class' body get executed at definition time?](https://stackoverflow.com/q/26193653/4518341) – wjandrea Jun 11 '20 at 19:22

2 Answers2

3

Code inside a class statement is executed immediately, as part of executing the class statement. Your code is roughly equivalent to

# Execute the body of the class statement
print("hello")
value = 44
def __init__(self):
    print("init")

# Call type, passing names defined in the body as a dict
# as the third argument
A = type("A", (), {'value': value, '__init__': __init__})

# Clean up the names, as they are not left in the global namespace
del value, __init__

Once the class A is defined, the only code that gets executed upon instantiation is the body of _init: a = A() is roughly equivalent to

a = A.__new__(A)
a.__init__()
chepner
  • 497,756
  • 71
  • 530
  • 681
1

From the docs:

Class definitions, like function definitions (def statements) must be executed before they have any effect. (You could conceivably place a class definition in a branch of an if statement, or inside a function.)

...

In practice, the statements inside a class definition will usually be function definitions, but other statements are allowed, and sometimes useful

Community
  • 1
  • 1
chash
  • 3,975
  • 13
  • 29