[英]Why is nonlocal keyword being 'interrupted' by a global keyword?
I'm a beginner programmer trying to learn python, and I have come across the topic of scopes. 我是一个初学程序员,正在尝试学习python,我遇到了范围主题。 I came across the error 'no binding for nonlocal var_name found' when executing the bottom-most code.
在执行最底层的代码时,我遇到了错误'找不到非本地var_name的绑定'。 Can someone explain why is the nonlocal keyword unable to 'look past' the intermediate function and into the outer function?
有人可以解释为什么nonlocal关键字无法“超越”中间函数并进入外部函数?
#this works
globe = 5
def outer():
globe = 10
def intermediate():
def inner():
nonlocal globe
globe = 20
print(globe)
inner()
print(globe)
intermediate()
print(globe)
outer()
globe = 5
def outer():
globe = 10
def intermediate():
global globe #but not when I do this
globe = 15
def inner():
nonlocal globe #I want this globe to reference 10, the value in outer()
globe = 20
print(globe)
inner()
print(globe)
intermediate()
print(globe)
outer()
Expressions involving the nonlocal
keyword will cause Python to try to find the variable in the enclosing local scopes, until it first encounters the first specified variable name . 涉及
nonlocal
关键字的表达式将导致Python尝试在封闭的本地范围中查找变量,直到它首次遇到第一个指定的变量名 。
The nonlocal globe
expression will have a look if there is a variable named globe
in the intermediate
function. nonlocal globe
表达式将查看intermediate
函数中是否存在名为globe
的变量。 It will encounter it, in the global
scope however, so it will presume it has reached the module scope and finished searching for it without finding a nonclocal
one, hence the exception. 然而,它会在
global
范围内遇到它,因此它会假定它已经达到模块范围并且在没有找到非nonclocal
范围的情况下完成搜索它,因此是例外。
By declaring the global globe
in the intermediate
function you pretty much closed the path to reach any nonlocal
variables with the same name in the previous scopes. 通过在
intermediate
函数中声明global globe
,您几乎关闭了在前一个作用域中使用相同名称访问任何nonlocal
变量的路径。 You can have a look at the discussion here why was it "decided" to be implemented this way in Python. 您可以在这里查看讨论为什么“决定”在Python中以这种方式实现。
If you want to make sure that the variable globe
is or is not within the local scope of some function, you can use the dir()
functions, because from Python docs : 如果要确保变量
globe
是否在某个函数的局部范围内,可以使用dir()
函数,因为来自Python文档 :
Without arguments, return the list of names in the current local scope.
如果没有参数,则返回当前本地范围中的名称列表。 With an argument, attempt to return a list of valid attributes for that object.
使用参数,尝试返回该对象的有效属性列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.