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

2024-04-26 11:41:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python3.7中有以下函数

def output_report():
    sheet_dict = {1: 'All', 2: 'Wind', 3: 'Soalr'} 
    sheet_name = sheet_dict[sheet_num]
    file_name = f'{file_name}_{sheet_name}_row_{row_num}.csv' if row_num else 
    f'{file_name}_{sheet_name}.csv'
    return file_name

def test_file(x):
    file_name = output_report(sheet_num)
    return f'{x}_{file_name}'

def good_func():
    sheet_num = 2
    row_num = 2
    a = test_file('new file')
    return a

当我呼叫:good_func()

它引发了一个错误:

NameError: name 'sheet_num' is not defined

但是如果我在全局范围内定义sheet\u name和row\u num,比如

sheet_num = 2
row_num = 2
def good_func():
    a = test_file('new file')
    return a

代码起作用了。你知道吗

我的问题:我的理解是,在嵌套函数中,内部函数从自身开始寻找变量,然后到外部函数,最后到全局范围。然后,我希望第一个函数也能运行,但事实并非如此。那是什么? 我读了其他的scope related questions,但没有找到我的答案。你知道吗


Tags: csv函数nametestreportoutputreturndef
1条回答
网友
1楼 · 发布于 2024-04-26 11:41:07

你的第一个案子

def good_func():
    sheet_num = 2
    row_num = 2
    a = test_file('new file')
    return a

sheet_numrow_num是函数good_func的本地函数,因此不能在另一个函数output_report中访问

但当你这么做的时候

sheet_num = 2
row_num = 2
def good_func():
    a = test_file('new file')
    return a

sheet_numrow_num成为所有其他函数都可以访问的全局变量,因此它们在output_report中也可以访问

嵌套函数也是其定义位于另一个函数中的函数,例如,a可以在inner中访问

def outer():
    a = 1
    def inner():
        print(a)
    inner()

outer()

像在good_func中那样在函数中调用另一个函数不会使它们output_function嵌套。你知道吗

相关问题 更多 >