Skip to main content
 首页 » 编程设计

python之嵌套函数中变量引用和赋值的顺序

2024年10月01日7dflying

来自Google Style Guide关于词法范围:

A nested Python function can refer to variables defined in enclosing functions, but can not assign to them.

可以在这里看到这个规范:

def toplevel(): 
    a = 5 
    def nested(): 
        # Tries to print local variable `a`, but `a` is created locally after, 
        # so `a` is referenced before assignment.  You would need `nonlocal a` 
        print(a + 2) 
        a = 7 
    nested() 
    return a 
toplevel() 
# UnboundLocalError: local variable 'a' referenced before assignment 

反转 nested 中两个语句的顺序可以解决这个问题:

def toplevel(): 
    a = 5 
    def nested(): 
        # Two statements' order reversed, `a` is now locally assigned and can 
        # be referenced 
        a = 7 
        print(a + 2) 
    nested() 
    return a 
toplevel() 

我的问题是,Python 的实现是什么 告诉第一个函数 a 将在本地声明(在 print 语句之后)?我的理解是 Python 是逐行有效解释的。那么,它不应该默认在代码中的那个点寻找非本地 a 吗?

详细来说,如果我要使用只是引用(没有赋值),

def toplevel(): 
    a = 5 
    def nested(): 
        print(a + 2) 
    nested() 
    return a 
toplevel() 

打印语句以某种方式知道引用封闭函数中定义的非局部a。但是,如果我在该行之后分配给本地 a ,该函数就其自身而言几乎太智能了。

请您参考如下方法:

My understanding is that Python is effectively interpreted line by line.

这不是正确的心智模型。

分析整个函数的主体以确定哪些名称引用局部变量,哪些不引用。

为了简化您的示例,以下还给出了 UnboundLocalError:

def func(): 
  print(a) 
  a = 2 
 
func() 

此处,func() 编译为以下字节码:

  2           0 LOAD_FAST                0 (a) 
              3 PRINT_ITEM 
              4 PRINT_NEWLINE 
 
  3           5 LOAD_CONST               1 (2) 
              8 STORE_FAST               0 (a) 
             11 LOAD_CONST               0 (None) 
             14 RETURN_VALUE 

比较一下

def gunc(): 
  print(a) 

编译成

  2           0 LOAD_GLOBAL              0 (a) 
              3 PRINT_ITEM 
              4 PRINT_NEWLINE 
              5 LOAD_CONST               0 (None) 
              8 RETURN_VALUE 

观察缺少对 a 的赋值如何将引用从本地引用转变为全局引用。