Why does this class run?

前端 未结 4 1450
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-21 13:13

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

相关标签:
4条回答
  • 2020-12-21 13:59

    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.

    0 讨论(0)
  • 2020-12-21 14:05

    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".

    0 讨论(0)
  • 2020-12-21 14:12

    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.

    0 讨论(0)
  • 2020-12-21 14:14

    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.

    0 讨论(0)
提交回复
热议问题