Python查询中的闭包

2024-04-25 21:28:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解Python中的Closures,并遇到了以下代码:

def return_func_that_prints_list(z):
    def f():
        print z
    return f

z = [1,2]
g = return_func_that_prints_list(z)
g()

# Output is [1,2,3]
z.append(3)
g()

我不理解这里的输出:

# Why is the Output still [1,2,3]?
z = [1]
g()

我不理解这里的输出:

# Why is the Output still [1,2,3]?
z.append(4)
g()

谢谢


Tags: the代码outputreturnthatisdefprints
1条回答
网友
1楼 · 发布于 2024-04-25 21:28:37

这一行:

z = [1]

重新绑定z,使其不再指向闭包中包含的对象。但是闭包仍然有它自己的旧对象副本,因此它的行为不会改变

相关问题 更多 >

    热门问题