What exactly are the Python scoping rules?
Python的作用域规则到底指的是什么?
If I have some code:
如果我有一段代码:
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
Where is x found? Some possible choices include the list above:
x在哪里能找到?可能的选择列举如下:
- In the enclosing source file 在闭包源文件中
- In the class namespace 在类命名空间里
- In the function definition 在函数定义中
- In the for loop index variable 在循环索引x变量中
- Inside the for loop 在for循环里
Also there is the context during execution, when the function spam is passed somewhere else. And maybe lambda functions pass a bit differently?
此外在运行过程中当函数spam被传给别的地方时有上下文环境。是不是lambda函数的传递会有些不同?
There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.
肯定在什么地方有一个简单的引用或者算法。这对Python程序员来说非常容易混淆。
Actually, a concise rule for Python Scope resolution, from Learning Python, 3rd. Ed.. (These rules are specific to variable names, not attributes. If you reference it without a period, these rules apply)
实际上,在《Python学习手册 第3版》书中有关于Python作用域解析规则的简明介绍。(这些规则专用于变量名称,而不是属性。)
LEGB Rule.
LEGB规则
L. Local. (Names assigned in any way within a function (def
or lambda
)), and not declared global in that function.
E. Enclosing function locals. (Name in the local scope of any and all enclosing functions (def
or lambda
), form inner to outer.
G. Global (module). Names assigned at the top-level of a module file, or declared global in a def
within the file.
B. Built-in (Python). Names preassigned in the built-in names module : open
,range
,SyntaxError
,...
L. 局部.(函数(def 或者 lambda)中的名字),并且没有在函数中声明为全局
E. 局部闭包函数. (局部作用域内明明的闭包函数(def 或者 lambda),从内部到外部
G. 全局(模块). 模块文件顶层的名字,或者在文件内的deff中声明为global
B. 内置(Python). 预定义在内部模块中的名字 : open
,range
,SyntaxError
,...
So, in the case of 所以在这个例子中
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
The for loop does not have it's own namespace. It would look in the LEGB order,
for循环没有属于它自己的命名空间。它会遵从LEGB顺序,
L : local, in the current def.
L:局部,当前的def块
E : Enclosed function, any enclosing functions(if def spam was in another def)
E:闭包函数,所有闭包函数(如果def spam位于另一个def中)
G : Global. Were there any declared globally in the module?
G:全局。模块中有声明为全局的变量吗?
B : Any builtin x() in Python.
B:任何Python内置的函数x()
本文链接:http://bookshadow.com/weblog/2014/05/15/python-legb-rules/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。