Python 中有关nonlocal的问题

Write a function that takes in no arguments and returns two functions, prepend and
get, which represent the “add to front of list” and “get the ith item” operations,
respectively. Do not use any python built-in data structures like lists or dictionaries.
翻译一下就是:写一个无参数方程,返回两个方程,一个prepend一个get. prepend用于添加数字,get用于获得数字。方程中不能适合用list和dictionary,每次添加数字进prepend中,都会被置于第一个位置,get最后放进去的数字则可以call get(0):
以下是功能展示:

prepend, get = nonlocalist()
prepend(2)
prepend(3)
prepend(4)
get(0)
4
get(1)
3
get(2)
2
prepend(8)
get(2)
3

答案是这样的,没完全弄懂,

def nonlocalist():
..................get = lambda x: 'Index out of range!'
..................def prepend(value):
.........................nonlocal get
.........................f=get
.........................def get(i):
................................if i==0:
........................................return value
................................return f(i-1)
...................return prepend,lambda x: get(x)

有没有大神知道这个应该怎么理解啊???先谢谢了!!!

这样的程序,你居然不给排好版,果然是得到了它的真传:劝退专用

def nonlocalist():
    """
    prepend: "add to front of list"
    get: "get the ith item"

    >>> prepend, get = nonlocalist()
    >>> prepend(2)
    >>> prepend(3)
    >>> prepend(4)
    >>> get(0)
    4
    >>> get(1)
    3
    >>> get(2)
    2
    >>> prepend(8)
    >>> get(2)
    3
    """
    get = lambda x: "Index out of range!"
    def prepend(value):
        nonlocal get
        f = get
        def get(i):
            if i == 0:
                return value
            return f(i-1)
    return prepend, lambda x: get(x)

把这段代码贴到python tutor里研究下过程就知道了。传送门:

http://pythontutor.com/visualize.html#mode=display