为什么分配给我的全局变量在 Python 中不起作用?

发布时间:2023-03-07 / 作者:清心寡欲
本文介绍了为什么分配给我的全局变量在 Python 中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在试图理解 Python 范围规则时遇到了严重的麻烦.

使用以下脚本:

a = 7定义打印A():打印a 的值是 %d" % (a)定义集A(值):a = 值打印在 setA 中,a 现在是 %d" %(a)打印在setA之前"打印A()集A(42)打印在 setA 之后"打印A()

给出意想不到的(对我来说)输出:

设置A之前a 的值为 7在 setA 中,a 现在是 42设置A后a 的值为 7

我希望 a 的最后一次打印的值是 42,而不是 7.关于 Python 的全局变量范围规则,我遗漏了什么?

解决方案

全局变量是特殊的.如果您尝试在函数内部为变量 a = value 赋值,它会在函数内部创建一个新的局部变量,即使存在同名的全局变量.要访问全局变量,请添加 global函数内的语句:

a = 7定义集A(值):global a # 声明 a 为全局a = value # 设置 a 的全局值

另请参阅命名和绑定以获取详细说明Python 的命名和绑定规则.

I'm having terrible trouble trying to understand python scoping rules.

With the following script:

a = 7

def printA():
    print "Value of a is %d" % (a)

def setA(value):
    a = value
    print "Inside setA, a is now %d" %(a)


print "Before setA"
printA()
setA(42)
print "After setA"
printA()

Gives the unexpected (to me) output of:

    Before setA
    Value of a is 7
    Inside setA, a is now 42
    After setA
    Value of a is 7

Where I would expect the last printing of the value of a to be 42, not 7. What am I missing about Python's scope rules for the scoping of global variables?

解决方案

Global variables are special. If you try to assign to a variable a = value inside of a function, it creates a new local variable inside the function, even if there is a global variable with the same name. To instead access the global variable, add a global statement inside the function:

a = 7
def setA(value):
    global a   # declare a to be a global
    a = value  # this sets the global value of a

See also Naming and binding for a detailed explanation of Python's naming and binding rules.

这篇关于为什么分配给我的全局变量在 Python 中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持吉威生活!



[英文标题]Why does assigning to my global variables not work in Python?


声明:本媒体部分图片、文章来源于网络,版权归原作者所有,如有侵权,请联系QQ:330946442删除。