Edit 1:
当您在 python 中调用自定义函数时,它必须知道它在文件中的位置。我们用def function_name():
定义我们在脚本中使用的函数的位置。我们必须打电话def function_name():
在我们打电话之前function_name()
,否则脚本不会知道function_name()
并会引发异常(函数未找到错误)。
通过跑步def function_name():
它只让脚本知道有一个函数叫做function_name()
但它实际上并没有运行里面的代码function_name()
直到你调用它。
在你的第二个例子中你打电话python()
在脚本到达之前def python()
,所以它不知道什么python()
is yet.
The 实施例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()
The 实施例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")
The 实施例2解决方案是:
1. def python(): # Python now knows about function python()
3. print("testing main")
2. python()
Edit 2:重申一下实施例1从脚本的角度来看:
def hello():
def python():
if __name__ == "__main__":
hello()
print("hello world")
python()
print("testing main")
这是脚本查看和运行每行代码的顺序。很明显脚本知道python()
因为 def 在第 #2 行被调用,并且python()
在第 6 行调用。
看来您不明白范围在定义方面的含义。阅读相关内容。函数的作用域不在 def 期间执行,仅在调用函数时执行。