I\'ve been playing with my codes a little for a while, and this one is not about a bug or anything, but i just don\'t understand why class main() runs without needing to ini
When Python read your code, it looked into class vars and defined all the variables. Then, it went into class main and executed the code there, as well as defining init. Python just executes whatever which is not in a function definition.
Unlike many other languages, class body is an executable statement in Python and is executed immediately as the interpreter reaches the class
line. When you run this "program":
class Foo:
print("hey")
it just prints "hey" without any Foo
object being created.
The same applies to the function definition statement def
(but not to function bodies). When you run this:
def foo(arg=print("hi")):
print("not yet")
it prints "hi", but not "not yet".
When a class is created, Python executes all of the code directly inside the class declaration in a new namespace. This is so that any variables created in the class (most commonly methods, created by ordinary function declarations like def foo(self...)
) are attached to the class rather than being global.
But the code still runs immediately. If it calls print()
or does something else which creates a visible side effect, that will happen now, not when the class is instantiated (called to create a new instance). If you need something to happen when the class is instantiated, write an __init__()
method instead.
main
is a class
not a function. Thus the code contained in the class
declaration runs immediately because all statements are executed as they appear in code. As a method declaration is reached, it's bound to the class as a member, so in a way methods execute as well but are not called.