Skip to main content
 首页 » 编程设计

python之了解 Python 中嵌套函数中的变量作用域

2024年11月24日10thcjp

我在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_name 和 row_num,比如,

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

代码有效。

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

请您参考如下方法:

第一种情况

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

sheet_num 和 row_num 是函数 good_func 的局部变量,因此不能在另一个函数 output_report 中访问/p>

但是当你这样做的时候

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

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

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

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

像在 good_func 中那样在函数内部调用另一个函数不会使它们 output_function 嵌套。