简体   繁体   中英

Why globals() doesn't work

I am new to python and I wanted to simply change variables by using globals() but for some reason I keep getting same outpu (1, 2 ,3 instead a, b, c). What is wrong here?

cwp = "01"
aw_sg = "01"

a01 = 1
a02 = 2
a03 = 3

p01g01a01 = "a"
p01g01a02 = "b"
p01g01a03 = "c"

print a01, a02, a03


def load_db(a01, a02, a03, cwp, aw_sg):

    a01 = globals()["p%sg%sa01" % (cwp, aw_sg)]
    a02 = globals()["p%sg%sa02" % (cwp, aw_sg)]
    a03 = globals()["p%sg%sa03" % (cwp, aw_sg)]

    return a01, a02, a03

load_db(a01, a02, a03, cwp, aw_sg)

print a01, a02, a03

You used globals() function to access global variables, but you have assigned them to local variables inside the function, and it doesn't change the global variables. If you want to change the global variables you can reassign the returned values by function to global variables.

a01, a02, a03 = load_db(a01, a02, a03, cwp, aw_sg)
print a01, a02, a03

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