简体   繁体   中英

Global variables scope in modules

Following are my files and output. All I want to do is get Value of x after func1() as 20 . I have already referred to this answer . I want to know why this do not work? Is it necessary to use import globalVar instead of from globalVar import *

globalVar.py

#globalVar.py
x=10

fun1.py

from globalVar import *

def func1():
    global x
    x=20
    print("X in fun1",x)

main.py

from fun1 import *
from globalVar import *

print("X before fun1=",x)
func1()
print("X after fun1=",x)

Output:

X before fun1= 10  
X in fun1 20  
X after fun1= 10

Updated Answer:

Try This:

GlobalVar.py:

global x
x = 10

fun1.py:

import GlobalVar

def func1():
    GlobalVar.x = 20
    print("X in fun1", GlobalVar.x)

main.py:

from fun1 import *
from GlobalVar import *

print("X before fun1=", GlobalVar.x)
func1()
print("X after fun1=", GlobalVar.x)

Check this this will give you your desired output according to your question.

Hope this will help you! Thankyou! :)

Note: The globals table dictionary is the dictionary of the current module (inside a function, this is a module where it is defined, not the module where it is called)

The reason this does not work is that The fun1() method call in main.py doesn't return the updated value of x ie 20. which is why the scope of updated x is only in fun1 once the execution is over, the value is lost & when you print the value of x the third time it simply refers back to the global variable

Heres what you may do to make it work 1.fun1.py

from globalVar import *

def func1():
    global x
    x=20
    print("X in fun1",x)
    return x //here it returns the value of 20 to be found later

2.globalVar.py

x=10

3.main.py

from fun1 import *

print("X before fun1=",x)
x = func1()//here the updated value of x is retrived and updated, had you not done this the scope of x=20 would only be within the func1()
print("X after fun1=",x)

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