:当您在python中调用自定义函数时,它必须知道它在文件中的位置。我们def function_name():
用来定义在脚本中使用的函数的位置。我们必须在调用def function_name():
之前先调用function_name()
,否则脚本将不知道function_name()
并且将引发异常(函数未找到错误)。
通过运行def function_name():
它,只会让脚本知道有一个调用的函数,function_name()
但实际上在function_name()
您调用它之前不会在其中运行代码。
在第二个示例中,您是python()
在脚本到达之前调用的def python()
,因此尚不知道是什么python()
。
的 的顺序是:
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()
该 的顺序是:
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")
该 的解决办法是:
1. def python(): # Python Now kNows about function python()
3. print("testing main")
2. python()
从脚本角度 重申 :
def hello():
def python():
if __name__ == "__main__":
hello()
print("hello world")
python()
print("testing main")
这是脚本将看到并运行每一行代码的顺序。显然,该脚本知道python()
def是在第2python()
行调用的,在第6行是调用的。