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 函数的本地框架后会消失。