得之我幸 失之我命

when someone abandons you,it is him that gets loss because he lost someone who truly loves him but you just lost one who doesn’t love you.

Python 的 LEGB 规则

LEGB 含义:

L-Local(function);函数内的名字空间
E-Enclosing function locals;外部嵌套函数的名字空间(例如closure)
G-Global(module);函数定义所在模块(文件)的名字空间
B-Builtin(Python);Python内置模块的名字空间

LEGB 规则主要指导了 python 的变量作用域,并从上到下 查找,如果需要修改,那需要 nonlocal 关键字

LEGB 规定了查找一个名称的顺序为:local–>enclosing function locals–>global–>builtin

举个例子

1
2
3
4
5
6
7
8
9
10
11
12
x = 1 

def foo():
x = 2
def innerfoo():
x = 3
print 'locals ', x
innerfoo()
print 'enclosing function locals ', x

foo()
print 'global ', x

输出

1
2
3
locals  3
enclosing function locals 2
global 1

改动一

1
2
3
4
5
6
7
8
9
10
11
12
x = 1 

def foo():
x = 2
def innerfoo():
# x = 3
print 'locals ', x
innerfoo()
print 'enclosing function locals ', x

foo()
print 'global ', x

输出

1
2
3
locals  2
enclosing function locals 2
global 1

改动二

1
2
3
4
5
6
7
8
9
10
11
12
x = 1 

def foo():
# x = 2
def innerfoo():
# x = 3
print 'locals ', x
innerfoo()
print 'enclosing function locals ', x

foo()
print 'global ', x

输出

1
2
3
locals  1
enclosing function locals 1
global 1

可以发现:当注释掉 x = 3x = 2 以后,函数 innerfoo 内部查找到的 x 是 x = 1

在上述例子中,从内到外,依次形成四个命名空间:

def innerfoo():Local,即函数内部命名空间;
def foo():Enclosing function locals,外部嵌套函数的名字空间
module (文件本身):Global(module),函数定义所在模块(文件)的名字空间
Python 内置模块的名字空间:Builtin

改动一

首先在 Local 命名空间查找,没有找到,然后到 Enclosing function locals 命名空间查找,查找成功,然后调用

改动二

首先在 Local 命名空间查找,没有找到,然后到 Enclosing function locals 命名空间查找,没找到,到 Global 命名控件查找,找到,然后调用

be slow to promise and quick to perform.