为什么分配给我的全局变量在Python中不起作用? [英] Why does assigning to my global variables not work in Python?
问题描述
使用以下脚本:
<$ (a)
$ b $
$ b def printA():
printa的价值是%d% b set setA(value):
a = value
print在setA之前,a现在是%d%(a)
print在setA之前$ b $ b printA()
setA(42)
printAfter setA
printA()
给我意想不到的(对我)输出:
在setA $ b $之前b是7
在setA中,a现在是42
setA
之后的值是7
我希望最后一次打印的a的值是42,而不是7.我错过了关于全局变量作用域的Python范围规则吗?
全局变量是特殊的。如果您尝试在函数内部赋值变量 a = value
,它会在函数内部创建一个新的局部变量,即使存在一个具有相同名称的全局变量。要改为访问全局变量,请添加 global
语句:
a = 7
def setA(value ):
global a#声明一个全局
a = value#这设定了
的全局值$ / code>
另请参阅命名和绑定详细解释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中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!