简体   繁体   English

Python 中的内部 function 中传输变量的差异

[英]Difference in transmitting variables in an inner function in Python

In Python, is there a difference between the following two codes both of which gives the same result c = [0,-10]?在 Python 中,以下两个代码之间是否存在差异,两者都给出相同的结果 c = [0,-10]?

def foo1():
    a = [0,1]

    def foo2():
        a[1] = -10

    foo2()
    return a


c = foo1()

and

def foo1():
    a = [0,1]

    def foo2(b):
        b[1] = -10

    foo2(a)
    return a


c = foo1()

Some commentator suggests this is answered by this question .一些评论员认为这个问题可以回答这个问题 But it does not since my question asks about the passing of variables through an inner function whilst the linked question does not.但它没有,因为我的问题是关于通过内部 function 传递变量,而链接的问题没有。

In the first, a is a free variable whose value is taken from the nearest enclosing scope (in this case, the scope of foo1 ) that defines a .首先, a是一个自由变量,其值取自定义a的最近的封闭 scope(在本例中为foo1的 scope)。

In the second, b is a local variable initialized using the argument passed to foo2 when it is called, which is the variable a defined in foo1 .在第二个中, b是一个局部变量,在调用它时使用传递给foo2的参数进行初始化,它是在foo1中定义的变量a

In each case, you assign -10 to the second "slot" of the same list.在每种情况下,您都将-10分配给同一列表的第二个“槽”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM