了解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()
您调用它之前不会在其中运行代码。
在第二个示例中,您是python()
在脚本到达之前调用的def 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是在第2python()
行调用的,在第6行是调用的。
看来您不了解定义范围的含义。阅读有关它。函数的作用域在定义期间不会执行,仅在调用函数时才执行。