Python函数全局变量? [英] Python function global variables?
问题描述
我知道我应该首先避免使用全局变量,因为这样会造成混淆,但是如果我要使用它们,下面是使用它们的有效方法吗? (我试图调用在单独函数中创建的变量的全局副本)。
x = somevalue
def func_A():
全局x
#将事物转换为x
返回x
def func_B():
x = func_A )
#做事
return x
func_A()
func_B()
第二个函数使用的 x
是否具有全局副本 x
func_a
使用并修改?在定义后调用函数时,顺序是否重要?
如果您只想访问全局变量,只需使用其名称。但是,要更改其值,您需要使用 全球
关键字。
例如
global someVar
someVar = 55
这会改变全局变量为55.否则它只会将55赋值给一个局部变量。
函数定义列表的顺序并不重要(假设它们并不是每个其他以某种方式),他们被称为的顺序。
I know I should avoid using global variables in the first place due to confusion like this, but if I were to use them, is the following a valid way to go about using them? (I am trying to call the global copy of a variable created in a separate function.)
x = somevalue
def func_A ():
global x
# Do things to x
return x
def func_B():
x=func_A()
# Do things
return x
func_A()
func_B()
Does the x
that the second function uses have the same value of the global copy of x
that func_a
uses and modifies? When calling the functions after definition, does order matter?
If you want to simply access a global variable you just use its name. However to change its value you need to use the global
keyword.
E.g.
global someVar
someVar = 55
This would change the value of the global variable to 55. Otherwise it would just assign 55 to a local variable.
The order of function definition listings doesn't matter (assuming they don't refer to each other in some way), the order they are called does.
这篇关于Python函数全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!