Skip to main content
 首页 » 编程设计

python变量范围LEGB规则

2024年12月31日13jyk

def fun(): 
    print b 
 
def pass_a(b): 
    fun() 

.

pass_a(2) raise: NameError: global name 'b' is not defined. 

按照LEGB规则,我以为找到b,python会上栈帧,在封闭作用域pass_a中找到b?请纠正我的理解。谢谢。

请您参考如下方法:

LEGB 中的“Enclosing”范围指的是lexically enclosed范围。

在下面的示例中,b 是一个可以在封闭范围内找到的名称:

def pass_a(b): 
    def fun(): 
        print(b) 
    fun() 

在您的示例中,b 包含在(不同的)本地范围内,而不是封闭范围内。

参见 PEP 3104 -- Access to Names in Outer Scopes .