[英]Assigning global variables in python to a single variable or function?
I think I grasp why global variables have to be used to bind variables in and outwith functions. 我想我理解为什么必须使用全局变量将变量绑定到函数中以及函数外。 So if I call:
因此,如果我致电:
x = 0
y = 0
z = 0
def example():
global x
global y
global z
I'll be able to alter x, y, z that are outside of the function. 我将能够更改函数外部的x,y,z。
However, is there a way to assign all of my needed global variables to something else and then calling them in one line. 但是,有一种方法可以将我需要的所有全局变量分配给其他对象,然后在一行中调用它们。
I tried: 我试过了:
def global_var():
global x
global y
global z
and then calling: 然后调用:
def example():
global_var()
x += 1
etc
But this doesn't seem to work. 但这似乎不起作用。 or at least the code seems to meet the x variable first and throws up a before assignment error.
或至少代码似乎先满足x变量并抛出前分配错误。
the keyword global has method scope therefore when you call it inside global_var() they will be available for modifications inside it. 关键字global具有方法作用域,因此,当您在global_var()中调用它时,它们将可用于其中的修改。 However when you return from it into example().
但是,当您从它返回到example()时。 Your global has no effect anymore therefor x is read only and you cannot modify its value.
您的全局变量不再有效,因此x是只读的,您不能修改其值。 You must get rid of gloval_var()
您必须摆脱gloval_var()
def example():
global x
global y
global z
x += 1
However if I can recommend you. 但是,如果我可以推荐您。 Don't use such method.
不要使用这种方法。 Use a dictionary if those variables are related somehow so you can sipmply do.
如果这些变量以某种方式相关,请使用字典,这样您就可以轻松地做到。
my_vars = {'x':0, 'y':0, 'z':0}
def example():
my_vars['x'] += 1
In this case, dictionary does not need the keyword global in order to be modified. 在这种情况下,字典不需要关键字global即可进行修改。 The reason behind this is that you are not assigning a new value but only modifying an existing object.
这背后的原因是您没有分配新值,而只是修改了现有对象。 If you write
x += 2
it means x = x + 2
which will result in a new assignment, that results in x
pointing to another value and this is not possible without global
. 如果您编写
x += 2
则意味着x = x + 2
,这将导致新的赋值,这将导致x
指向另一个值,并且如果没有global
则不可能。 However, if you modify my_vars, its memory address stays the same but only its data changes, since dict
is a mutable value. 但是,如果修改my_vars,则其内存地址保持不变,但仅更改其数据,因为
dict
是可变值。
You could create function that modifies global variables: 您可以创建修改全局变量的函数:
x = 0
y = 0
z = 0
def setGlobals(**vals):
for key, value in vals.iteritems():
globals()[key] = value
print x, z
setGlobals(x=5, z=3)
print x, z
output: 输出:
0 0
5 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.