范围规则的简短描述? [英] Short description of the scoping rules?
问题描述
什么是Python范围界定规则?
如果我有一些代码:
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
在哪里找到x
?一些可能的选择包括以下列表:
- 在随附的源文件中
- 在类命名空间中
- 在函数定义中
- 在for循环索引变量中
- 在for循环内
在执行过程中,当功能spam
被传递到其他地方时,也存在上下文.也许 lambda函数传递的方式有所不同吗?
某处必须有一个简单的参考或算法.对于中级Python程序员而言,这是一个令人困惑的世界.
What exactly are the Python scoping rules?
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 below:
- In the enclosing source file
- In the class namespace
- In the function definition
- In the for loop index variable
- Inside the for loop
Also there is the context during execution, when the function spam
is passed somewhere else. And maybe lambda functions pass a bit differently?
There must be a simple reference or algorithm somewhere. It's a confusing world for intermediate Python programmers.
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.)
LEGB Rule
Local — Names assigned in any way within a function (
def
orlambda
), and not declared global in that functionEnclosing-function — Names assigned in the local scope of any and all statically enclosing functions (
def
orlambda
), from inner to outerGlobal (module) — Names assigned at the top-level of a module file, or by executing a
global
statement in adef
within the fileBuilt-in (Python) — Names preassigned in the built-in names module:
open
,range
,SyntaxError
, etc
So, in the case of
code1
class Foo:
code2
def spam():
code3
for code4:
code5
x()
The for
loop does not have its own namespace. In LEGB order, the scopes would be
- L: Local in
def spam
(incode3
,code4
, andcode5
) - E: Any enclosing functions (if the whole example were in another
def
) - G: Were there any
x
declared globally in the module (incode1
)? - B: Any builtin
x
in Python.
x
will never be found in code2
(even in cases where you might expect it would, see Antti's answer or here).
这篇关于范围规则的简短描述?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!