简体   繁体   English

为什么 python 无法通过 function 参数名称更改访问全局变量值?

[英]why python can't access global variable value with function parameter name change?

in these two pieces of code, why the second one gives error about local variable assignment?在这两段代码中,为什么第二段给出局部变量赋值错误? two codes are similar just function parameters is different, in the second one it's able to read the global variable why not in the first one what changes with parameter name change about symbol table?两个代码相似,只是 function 参数不同,在第二个中它能够读取全局变量,为什么不在第一个中随着参数名称的变化而改变符号表?

first one:第一:

def a(z):
    z+=1
z=3
a(z)

second one:第二个:

def a(z):
    b += 1
b = 5
a(b)

You should concider def blocks as stand alone.您应该将def块视为独立的。

In the first snippet:在第一个片段中:

def a(z):
    z+=1

What is z ? z是什么? It's the first parameter of a这是a的第一个参数

In the second snippet:在第二个片段中:

def a(z):
    b += 1

What is b ?什么是b It is unknown.这是未知的。 That's why this code fails.这就是此代码失败的原因。

You should also notice that in your first snippet, z inside the function is not the same than z=3 :您还应该注意到,在您的第一个片段中, function 中的zz=3不同:

>>> def a(z):
...     z+=1
...
>>> z=3
>>> a(z)
>>>
>>> z
3

There aren't any global variables in use here.这里没有使用任何全局变量。

In the first example, z is a parameter to the function, not a global.在第一个示例中, z是 function 的参数,而不是全局参数。 Note that when you increment z , it does not change in the calling scope, because the z inside the function is a copy of the z you passed in from outside the function.请注意,当您增加z时,它不会在调用 scope 中发生变化,因为 function 内部的z是您从 ZC1C425268E68385D1AB5074C17A94F 外部传入的z的副本。

In the second example, there is no b inside the function (the parameter is z ), which is why you get an error inside the function when you try to modify it.在第二个示例中, function 中没有b (参数为z ),这就是为什么当您尝试修改 function 时会出现错误的原因。

To do what you're trying to do, you should make the parameter a mutable object that contains the value you're trying to mutate;要执行您想要执行的操作,您应该将参数设置为可变的 object ,其中包含您要更改的值; that way you can modify the value inside the function and the caller will have access to the new value.这样您就可以修改 function 中的值,调用者将可以访问新值。 You could define a class for this purpose, or you could simply make it a single-element list:您可以为此目的定义一个 class ,或者您可以简单地将其设为单元素列表:

def a(z):
    z[0] += 1
b = [5]
a(b)  # b == [6]

Or, if possible, a better approach IMO is not to depend on mutability, and to just return the new value, requiring the caller to explicitly re-assign it within its scope:或者,如果可能,更好的方法 IMO 不依赖于可变性,而只返回新值,要求调用者在其 scope 中明确地重新分配它:

def a(z)
    return z + 1
b = 5
b = a(b)  # b == 6

In the second code, the parameter is "z", and you tried to access that parameter with "b"在第二个代码中,参数是“z”,您尝试使用“b”访问该参数

def a(z):
    b += 1

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

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