简体   繁体   中英

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.

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.

the keyword global has method scope therefore when you call it inside global_var() they will be available for modifications inside it. However when you return from it into example(). Your global has no effect anymore therefor x is read only and you cannot modify its value. You must get rid of 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. 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 . However, if you modify my_vars, its memory address stays the same but only its data changes, since dict is a mutable value.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM