1 def outer_func():
2 name = "Pythonista"
3 def inner_func():
4 print(f"Hello, {name}!")
5 inner_func()
6 outer_func()
执行顺序
1 → 6 → 1(进入 outer_func) → 2 → 3(定义 inner_func 并绑定到局部变量 inner_func) → 5 → 3(进入 inner_func) → 4 → 4 执行完返回 5 → 5 执行完返回 6 → 程序结束。
函数绑定(创建函数对象并与变量关联)的时间
• outer_func:在解释器执行到第 1 行时立即完成绑定(变量 outer_func 指向对应的函数对象)。
• inner_func:在每次调用 outer_func 并执行到第 3 行时才完成绑定(变量 inner_func 是 outer_func 的局部变量,每次进入 outer_func 都会重新创建并绑定一个新的函数对象)。