Python嵌套函数中的变量作用域

Python嵌套函数中的变量作用域

本文介绍了Python嵌套函数中的变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个代码段打印出 [0,3] out。



<$ p ():
a.append(3)
$ def func():
a = [0]

a = [1] + a
返回a
返回游泳()

print(func())
$ b

第二个代码片段引发错误UnboundLocalError:本地变量a在赋值之前引用

  def func():
a = [0]

def swim():
#a.append(3)
a = [1] + a
返回a
返回游泳()

print(func())

是 a 可见/可访问的功能 swim 毕竟?

解决方案

看来这是一个常见问题,如此链接。原因是 swim 中的变量 a 在赋值为<$ c $时立即变为局部变量C> A 。它隐藏了外部 a ,并且在函数 swim <中分配之前未定义本地 a / code>,所以错误上升。



感谢所有人的回答!

The first code snippet prints [0, 3] out.

def func():
    a = [0]

    def swim():
        a.append(3)
        # a = [1]+a
        return a
    return swim()

print(func())

The second code snippet raises error "UnboundLocalError: local variable 'a' referenced before assignment"

def func():
    a = [0]

    def swim():
        # a.append(3)
        a = [1]+a
        return a
    return swim()

print(func())

Is a visible/accessible to function swim after all?

解决方案

It seems this is a commonly asked question as stated in this link. The reason is that variable a inside swim becomes a local variable as soon as there is an assignment to a. It shadows the external a, and local a is not defined before assignment in function swim, so the error rises.

Thanks for all your guys' answers!

这篇关于Python嵌套函数中的变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 11:46