java里不可以方法里嵌套方法,但是python可以
global - myprogram.py
spam - “global spam”
function - scope_test()
spam = “test spam”
= “nonlocal spam”
local - do_local()
spam = “local spam”
注意print()打印出的内容,始终在scope_test()方法下,所以它打印出的spam永远都是 function spam。
下面是详细的运行过程:
- 程序执行scope_test方法,该方法下spam = “test spam”
- 程序开始执行do_local()方法,注意do_local方法里赋值的是local spam, 它并不影响 function spam。 所以此时打印的结果为:After local assignment: test spam
- 程序开始执行do_nonlocal()方法,注意这个方法里的nonlocal spam, nonlocal 改变的是function spam, 所以此时function spam变成了“nonlocal spam”, 打印结果为**“After nonlocal assignment: nonlocal spam”**
- 程序开始执行do_global()方法,注意这个方法里的global spam, global 改变的是global spam, 所以此时global spam变成了“global spam”, 但function spam仍然还是"nonlocal spam",因此打印结果为**“After global assignment: nonlocal spam”**
- scope_test()方法结束,该文件myprogram.py开始调用scope_test()
def scope_test():
def do_local():
spam = "local spam"
def do_nonlocal():
nonlocal spam
spam = "nonlocal spam"
def do_global():
global spam
spam = "global spam"
spam = "test spam"
do_local()
print("After local assignment:", spam)
do_nonlocal()
print("After nonlocal assignment:", spam)
do_global()
print("After global assignment:", spam)
scope_test()
print("In global scope:", spam)
运行结果: