Why does this class run?

前端 未结 4 1451
爱一瞬间的悲伤
爱一瞬间的悲伤 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 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".

提交回复
热议问题