【发布时间】:2018-09-18 23:11:31
【问题描述】:
def make_test_dice(*outcomes):
"""Return a die that cycles deterministically through OUTCOMES.
>>> dice = make_test_dice(1, 2, 3)
>>> dice()
1
>>> dice()
2
>>> dice()
3
>>> dice()
1
"""
assert len(outcomes) > 0, 'You must supply outcomes to make_test_dice'
for o in outcomes:
assert type(o) == int and o >= 1, 'Outcome is not a positive integer'
index = len(outcomes) - 1
print("Index1: ", index)
def dice():
nonlocal index
index = (index + 1) % len(outcomes)
print("Index2: ", index)
return outcomes[index]
return dice
def main():
foursided = make_test_dice(4,1,2)
foursided()
foursided()
if __name__ == "__main__": main()
所以我意识到,在调用 make_test_dice 之后,当调用foursided 时,它会跳过 index1 var 的打印并转到 dice 函数,因为这是一个闭包。我知道非局部变量是指封闭范围内的变量,因此更改嵌套函数中的 var 会在外部更改它,但我不明白 index 变量如何存储在嵌套函数中,因为它在 dice() 中设置值时需要一个值索引。鉴于我的打印语句,我相信它可能是 index 的先前值,但我认为 index 在我们退出 make_test_dice 函数的本地框架后会消失。
【问题讨论】:
-
请不要重复问题stackoverflow.com/questions/49729112/…,正如我所说,请阅读
nonlocal的作用 stackoverflow.com/questions/1261875/python-nonlocal-statement -
我确实读过 nonlocal 做了什么,但它没有回答索引变量是如何在函数调用之间存储的。我知道 nonlocal 使外部函数作用域中的变量在内部作用域中可变,而不创建同名的新 var,但这并不能回答我的主要问题。
-
你似乎不明白
nonlocal,因为这解释了index是如何更新的,有点像global。试试这个,x = 0然后def f(): global x: x += 1,然后多次调用f()和print(x)
标签: python python-3.x closures python-nonlocal