我试图理解Python中的名称空间。你知道吗
我尝试了Python文档中给出的这个场景。你知道吗
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"
do_local()
print("before local assignment:", spam)
do_nonlocal()
print("before nonlocal assignment:", spam)
do_global()
print("before global assignment:", 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)
这不能说明:
The variable spam is referenced before its declared.
我已经在dou local()中清楚地定义了变量。你知道吗
我从一个简单的例子开始:我尝试访问一个没有在任何地方定义的非局部变量。这将失败:
这很容易解决:我只需在适当的范围内添加此变量:
现在我想添加一个本地版本的函数,让事情变得更有趣:
它再次失败:我稍后定义
spam
没有帮助(太晚了),而且do_local
在本地分配给spam
也没有帮助:函数scope_test3
没有看到这个本地版本。你知道吗我可能会尝试通过添加我的非本地版本来缓解这种情况:
但这也没什么帮助:
do_nonlocal
不会仅仅通过存在就神奇地将spam
添加到它的非局部范围。你知道吗相关问题 更多 >
编程相关推荐