小编Lia*_* Li的帖子

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

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

def func():
    a = [0]

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

print(func())
Run Code Online (Sandbox Code Playgroud)

第二个代码片段引发错误“UnboundLocalError:赋值前引用的局部变量‘a’”

def func():
    a = [0]

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

print(func())
Run Code Online (Sandbox Code Playgroud)

到底a功能是否可见/可访问?swim

python scope function global-variables python-3.x

5
推荐指数
1
解决办法
4036
查看次数

标签 统计

function ×1

global-variables ×1

python ×1

python-3.x ×1

scope ×1