Python 嵌套函数变量作用域

标签 python variables scope

我已经阅读了有关该主题的几乎所有其他问题,但我的代码仍然无法正常工作。

我想我遗漏了一些关于 python 变量范围的东西。

这是我的代码:

PRICE_RANGES = {
                64:(25, 0.35),
                32:(13, 0.40),
                16:(7, 0.45),
                8:(4, 0.5)
                }

def get_order_total(quantity):
    global PRICE_RANGES
    _total = 0
    _i = PRICE_RANGES.iterkeys()
    def recurse(_i):
        try:
            key = _i.next()
            if quantity % key != quantity:
                _total += PRICE_RANGES[key][0]
            return recurse(_i) 
        except StopIteration:
            return (key, quantity % key)

    res = recurse(_i)

我明白了

"global name '_total' is not defined"

我知道问题出在 _total 分配上,但我不明白为什么。 recurse() 不应该访问父函数的变量吗?

有人可以向我解释一下我对 python 变量作用域的遗漏吗?

最佳答案

在 Python 3 中,您可以使用 nonlocal statement访问非本地、非全局范围。

nonlocal 语句使变量定义绑定(bind)到最近范围内先前创建的变量。下面举几个例子来说明:

def sum_list_items(_list):
    total = 0

    def do_the_sum(_list):
        for i in _list:
            total += i

    do_the_sum(_list)

    return total

sum_list_items([1, 2, 3])

上面的例子会失败并报错:UnboundLocalError: local variable 'total' referenced before assignment

使用 nonlocal 我们可以让代码工作:

def sum_list_items(_list):
    total = 0

    def do_the_sum(_list):

        # Define the total variable as non-local, causing it to bind
        # to the nearest non-global variable also called total.
        nonlocal total

        for i in _list:
            total += i

    do_the_sum(_list)

    return total

sum_list_items([1, 2, 3])

但是“最近”是什么意思?这是另一个例子:

def sum_list_items(_list):

    total = 0

    def do_the_sum(_list):

        # The nonlocal total binds to this variable.
        total = 0

        def do_core_computations(_list):

            # Define the total variable as non-local, causing it to bind
            # to the nearest non-global variable also called total.
            nonlocal total

            for i in _list:
                total += i

        do_core_computations(_list)

    do_the_sum(_list)

    return total

sum_list_items([1, 2, 3])

在上面的例子中,total 将绑定(bind)到 do_the_sum 函数中定义的变量,而不是 sum_list_items 中定义的外部变量函数,因此代码将返回 0。请注意,仍然可以进行这样的双重嵌套:如果在 do_the_sum 中声明了 total nonlocal,则上面的示例将按预期工作。

def sum_list_items(_list):

    # The nonlocal total binds to this variable.
    total = 0

    def do_the_sum(_list):

        def do_core_computations(_list):

            # Define the total variable as non-local, causing it to bind
            # to the nearest non-global variable also called total.
            nonlocal total

            for i in _list:
                total += i

        do_core_computations(_list)

    do_the_sum(_list)

    return total

sum_list_items([1, 2, 3])

在上面的例子中,非本地赋值在找到 sum_list_items 本地的 total 变量之前遍历了两个级别。

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

相关文章:

c - 如何编写一个程序来查找整型变量的最大值

javascript - 如何在javascript中将变量传递给回调函数

python - 如何在不使用单独的替换函数的情况下循环正则表达式匹配并进行替换?

python - Astropy 权限被拒绝错误

python - 无法从 'StandardScalar' 导入名称 'sklearn.preprocessing'

c - 初始化 block 部分不允许声明

php - 将 html/php 代码存储到 php 变量中

python 由于多次重复调用 pandas 而卡住

c - 是否有可能在 main 之后声明的变量具有文件范围?

php - 您可以解决 PHP 中超出范围的后期静态绑定(bind)吗?