python legb规则_Python LEGB作用域规则简述

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()

如果您喜欢这篇博文,欢迎您捐赠书影博客:

,查看支付宝二维码

×

捐赠书影博客

Close

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值