多模块Python程序的入口点是什么?

2024-06-09 13:25:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道Python程序从什么时候开始运行。我以前在Java工作过。在Java中,每个程序都从它的Main类的main()函数开始。知道了这一点,我可以确定其他类或其他类的函数的执行顺序。我知道在Python中,我可以使用__name__来控制程序的执行顺序,如下所示:

def main():
    print("This is the main routine.")

if __name__ == "__main__":
    main()

但是当我们不使用__name__那么我的Python程序的起始行是什么呢?在


Tags: the函数name程序if顺序ismain
1条回答
网友
1楼 · 发布于 2024-06-09 13:25:16

Interpreter starts to interpret file line by line from the beginning. If it encounters function definition, it adds it into the globals dict. If it encounters function call, it searches it in globals dict and executes or fail.

# foo.py
def foo():
    print "hello"
foo()

def test()
    print "test"

print "global_string"

if __name__ == "__main__":
    print "executed"
else:
    print "imported"

输出

^{pr2}$
  • 口译员开始翻译食品从一开始就逐行执行,就像首先将函数定义添加到globals dict中,然后遇到对函数foo()的调用并执行它,以便打印hello
  • 之后,它将test()添加到global dict,但没有对该函数进行函数调用,因此它不会执行该函数。
  • 之后,将执行print语句将打印global_string
  • 之后,if条件将执行,在本例中,它匹配并将打印executed。在

相关问题 更多 >