我已经阅读了有关该主题的几乎所有其他问题,但我的代码仍然无法正常工作。
我想我遗漏了一些关于 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/