Python全局变量/作用域混淆 [英] Python global variable/scope confusion

查看:132
本文介绍了Python全局变量/作用域混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始自学python,并且注意到与全局变量和作用域有关的一些奇怪的事情. 当我运行此命令时:

I've started teaching myself python, and have noticed something strange to do with global variables and scope. When I run this:

x = 2 
y = 3 
z=17 
def add_nums():
    y = 6 
    return z+y

打印23的结果... 但是,当我将返回值扩展为:

The result of 23 is printed... However, when I expand the return to be:

x = 2 
y = 3 
z=17 
def add_nums(): 
    y = 6 
    z = z + y 
    return z

在第6行出现以下错误:

I get the following error on line 6:

Local name referenced but not bound to a value.
A local name was used before it was created. You need to define the     
method or variable before you try to use it.


我很困惑为什么在这里出现错误,因为z是全局可访问的.


I'm confused as why I am getting an error here, as z is global an accessible.

推荐答案

当变量在等号的左侧时,python将创建一个局部变量.当变量位于等号的右侧时,python将尝试查找局部变量,如果他找不到局部变量,则它将使用全局变量.在您的示例中,z位于等号的右侧和左侧,以避免歧义python引发错误.您需要使用global语法来避免这种情况:

When a variable is on the left side of an equal sign python will create a local variable. When the variable is on the right side of the equal sign python will try to look for a local variable and if he can't find one then it will use a global variable. In your example, z is on the right and left side of the equal sign, to avoid ambiguities python raises an error. You need to use the global syntax to avoid this:

x = 2 
y = 3 
z=17 
def add_nums(): 
    global z
    y = 6 
    z = z + y 
    return z

这篇关于Python全局变量/作用域混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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