繁体   English   中英

理解python中的执行流程

[英]understanding the execution flow in python

刚接触python,对执行流程感到困惑:

为了详细说明,我正在说明以下示例:

示例 1:

def hello():
    print("hello world")
    python()

def python():
    print("testing main")

if __name__ == "__main__":
    hello()

**output :**
    hello world
    testing main

注意:我知道__name__ == "__main__"的用法

示例 2:

python()

def python():
    print("testing main")

**output**
File "main_flow.py", line 2, in <module>
python()
NameError: name 'python' is not defined

据我所知,python 以顺序方式执行程序(如果我错了,请纠正我),因此在示例 2 中,它在遇到方法 python() 时无法找到它。

我的困惑是为什么在示例 1 中没有发生类似的错误,这种情况下的执行流程是什么。

编辑 1 :当您在 python 中调用自定义函数时,它必须知道它在文件中的位置。 我们使用def function_name():来定义我们在脚本中使用的函数的位置。 我们必须调用def function_name():我们调用之前function_name()否则该脚本将不知道function_name()并会引发异常(找不到函数的错误)。

通过运行def function_name():它只让脚本知道有一个名为function_name()但在你调用它之前它实际上并没有运行function_name()的代码。

在您的第二个示例中,您在脚本到达def python() python()之前调用python() ,因此它还不知道python()是什么。

示例 1 的顺序是:

1.    def hello(): # Python now knows about function hello()
5.        print("hello world")
6.        python()

2.    def python(): # Python now knows about function python()
7.        print("testing main")

3.    if __name__ == "__main__":
4.       hello() 

示例 2 的顺序是:

1.    python()    # Error because Python doesn't know what function python() is yet

-     def python(): # Python doesn't reach this line because of the above error
-         print("testing main")

示例 2 的解决方案是:

1.     def python(): # Python now knows about function python()
3.         print("testing main")

2.     python()   

编辑 2:从脚本的角度重申示例 1

def hello(): 
def python(): 
if __name__ == "__main__":
hello() 
print("hello world")
python()
print("testing main")

这是脚本将看到和运行每行代码的顺序。 很明显,脚本知道python()因为 def 在第 2 行调用, python()在第 6 行调用。

当涉及到定义时,您似乎不明白范围的含义。 阅读它。 函数的作用域在 def 期间不执行,它只在函数被调用时执行。

不是__name__ == '__main__' ,而是因为被定义的函数执行之前在第二个例子中的函数调用。

您的第一个示例定义所有函数执行函数python 因为hello在函数定义之后调用(因此没有名称错误)!

如果将hello()放在定义之间,则会再次出现错误:

def hello():
    print("hello world")
    python()

hello()

def python():
    print("testing main")

给出:

hello world 
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-7-21db1c6bfff8> in <module>()
      3     python()
      4 
----> 5 hello()
      6 
      7 def python():

<ipython-input-7-21db1c6bfff8> in hello()
      1 def hello():
      2     print("hello world")
----> 3     python()
      4 
      5 hello()

NameError: name 'python' is not defined

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM