How/what 声明为 nonlocal 的嵌套函数中变量的值是否设置为?

How/what is the value of a variable in a nested function declared nonlocal set to?

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() 中设置值时需要一个值索引。根据我的 print 语句,我相信它可能是 index 的先前值,但我认为在我们退出 make_test_dice 函数的本地框架后 index 会消失。

I realize that after calling make_test_dice, when calling foursided it skips the printing of the index1 var and goes to the dice function,

什么都没有被跳过 - foursided 是 "the dice function"。或者,更确切地说,它是在 foursided = make_test_dice(4,1,2) 调用期间创建的函数对象 - 每次调用 make_test_dice() 都会创建一个新的 "dice" 函数。

as this is a closure

看来你并没有真正理解闭包到底是什么。

I understand that nonlocal variables refer to variables in the enclosing scope so that changing the var in the nested function would change it in the outer, but what I don't understand is how the variable of index is stored inside the nested function

嗯,这正是闭包的全部意义所在:它们确实捕获了定义它们的环境。在 Python 中,函数是对象(内置 function class 的实例), 他们只使用一个实例属性:

def show_closure(func):
    print(func.__closure__)
    for cell in func.__closure__:
        print(cell.cell_contents)


foursided = make_test_dice(4,1,2)
for i in range(4):
    show_closure(foursided)
    foursided()