Python查询中的闭包

Python查询中的闭包,python,Python,我试图理解Python中的闭包,并遇到了以下代码: 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(

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

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()
我不理解这里的输出:

# Why is the Output still [1,2,3]?
z = [1]
g()
# Why is the Output still [1,2,3]?
z.append(4)
g()
谢谢这一行:

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