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

标签 python python-3.x scope nested global-variables

我在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_numrow_num 是函数 good_func 的局部变量,因此不能在另一个函数 output_report 中访问/p>

但是当你这样做的时候

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 嵌套。

关于python - 了解 Python 中嵌套函数中的变量作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56303426/

相关文章:

JavaScript + jQuery 这个范围

python libcloud 在 vAPP 中创建虚拟机

python - 如何在使用 python 2.6.4 在 xml.etree.elementtree 中使用 XPaths 时获取父标记

Python 哈希值在线程之间有所不同

python - 永久更改 Linux 中的默认 Python3 版本(Windows 上的 Ubuntu)

python - python中列表列表之间的叉积

简单游戏的 Python 经验和等级点

python - 编写 "execute only"Python 模块的最佳实践是什么?

python - Flask - 将变量从 URL 传递给函数

javascript - 寻找一些 js 范围 hack