为什么python对变量有这种行为? [英] Why does python behave this way with variables?

查看:74
本文介绍了为什么python对变量有这种行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在下面的代码块中理解为什么 python 会这样.我已经完成了我的研究,但找不到一个好的答案,所以我来这里看看是否有人能指出我正确的方向或提供一个很好的澄清.我知道这与一些旧的 ALGOL 原则有关,但我并不完全理解.

I have been trying to understand why python behaves this way, in the block of code below. I have done my research but couldn't find a good answer so I came here to see if anyone can point me in the right direction or provide a good clarification. I understand that it has to do with some old ALGOL principle, but I don't fully understand it.

var = 5

def func1():
    print(var)
func1()

def func2():
    var = 8
    print(var)
func2()

def func3():
    print(var)
    var = 8
func3()

这段代码的输出如下:

The output of this code is as follows:

5
8
UnboundLocalError:赋值前引用了局部变量var"

我理解为什么我们得到输出5"和8".但是对于func3()",我期望输出为5".看起来,解释器认为我想在函数中打印本地var"而不是全局var".所以它抛出这个错误.

I understand why we get the outputs '5' and '8'. But with 'func3()', I was expecting an output of '5'. As it seems, the interpreter thinks that I want to print the local 'var' in the function instead of the global 'var'. So it throws this error.

或者,如果在函数内部某处定义了一个变量,那么该函数将默认为局部变量,而不是具有相同名称的全局变量.

Or maybe if a variable is defined somewhere inside of the function, then the function will default to the local variable, instead of a global one with the same name.

但是为什么python会这样呢?我不是在抱怨,我只是想了解一些东西...

But why exactly does python behave this way ? I am not complaining, I am just trying to understand something...

如何在函数中使用预定义的全局变量,然后在同一个函数中定义一个同名的局部变量,而不改变全局变量的值?(当然在python中)

How could I use a predefined global variable in a function, then define a local variable with the same name inside of the same function, without changing the value of the global variable ? ( in python of course )

在此先感谢大家.你们是了不起的人!:)

Thanks in advance to everyone here. You are amazing people ! :)

Edit_1:感谢大家的精彩回答.我完全理解在函数中使用预定义的全局变量,然后在同一个函数中定义一个具有相同名称的局部变量是一个糟糕且不切实际的想法.我只是从理论的角度考虑它,因为我在大学讲座中看到了它.XD我找不到一个单一的用例,在这种情况下,这样做也是最佳的!

Edit_2:我已经阅读了 PEP8,我知道显式比隐式更好.:)这是真的.否则代码会令人困惑并导致错误.这个问题只是关于我试图理解的一些无用且不切实际的大学理论.

Edit_3:现在我完全理解为什么会发生这种情况以及这里发生了什么.感谢 Randall Valenciano 提供此链接到 博客 很好地解释了这一点.

Edit_3: Now I fully understand why it happens and what is going on here. Thanks to Randall Valenciano for providing this link to a blog that explains it very well.

发生的情况是函数被解释为一个整体,而不是逐行解释.因此,当函数被解释时,任何已定义变量的变量声明都被移动到函数的顶部.因此,当我们打印var"时,该函数正在使用尚未分配任何值的本地声明变量,然后解释器会抱怨它并抛出错误.

What happens is that the function is interpreted as a whole, and not line by line. So when the function is being interpreted, the variable declarations of any defined variables, are moved to the top of the function. So when we are printing 'var', the function is using the locally declared variable that doesn't have any value assigned to it yet, and then the interpreter complains about it and throws and error.

再次感谢大家!:)你对我帮助很大!现在我终于明白幕后发生了什么.

Thanks to all of you again ! :) You have been of great help to me ! Now I finally understand what is going on there under the hood.

推荐答案

你的 var 被定义为一个全局变量.在每个函数中,当您只读取 var 时,您正在访问全局变量,但是当函数中的某处为 var 分配了值时,python 处理 every var 在函数中作为局部变量.因此,为什么你的最后一个函数失败了,因为 print(var) (局部变量)在 var = 8 被分配之前被调用.

Your var is defined as a global variable. In each function when you're only reading the var you're accessing the global var, but the moment there's an assigned value to var somewhere in the function, python treats every var within the function as a local variable. Thus why your last function failed, because print(var) (the local varaible) was called before var = 8 was assigned.

您可以在这些主题中了解更多信息:
在外部作用域中定义的影子名称有多糟糕?
Python 非本地语句

You can read up a bit about more in these threads:
How bad is shadowing names defined in outer scopes?
Python nonlocal statement

最好的做法是明确您的代码,这样您在尝试引用局部、非局部或全局变量时就不会再感到困惑.

The best thing to do is be explicit about your code so it's no longer confusing if you're trying to reference a local, nonlocal or global variable.

在这种情况下,假设您打算继续使用全局变量,请执行以下操作:

In this case, assuming your intention is to keep using the global var, do this:

var = 5

def func1():
    print(var)
func1()

def func2():
    global var
    var = 8
    print(var)
func2()

def func3():
    global var
    print(var)
    var = 8  # technically this is not necessary any more var = 8 was already assigned when func2() is called
func3()

输出如下:

5
8
8

感谢 juanpa.arrivillaga 的评论 - 我错过了您最初的问题.

Thanks to juanpa.arrivillaga's comment - I missed your original question.

如何在函数中使用预定义的全局变量,然后在同名的内部定义一个同名的局部变量函数,而不改变全局变量的值?( 在当然是蟒蛇)

How could I use a predefined global variable in a function, then define a local variable with the same name inside of the same function, without changing the value of the global variable ? ( in python of course )

简短的回答是 - 首先像您在 func2() 中所做的那样定义本地 var 并且您很好.更长的答案是 - 你为什么要这样做?当您在不同范围内拥有相同名称的变量时,它会造成混乱并变得令人头疼.更好的方法是将您的本地变量命名为 local_var 或其他名称,以便它明显不同且易于跟踪.

The short answer is - define the local var first like you did in func2() and you're good. The longer answer though is - why would you want to do that? It creates confusion and becomes a headache to track which is when you have variables of the same name in different scope. A better approach would be name your local var to be local_var or something so it's distinctly different and easily traced.

这篇关于为什么python对变量有这种行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆