模块中的全局变量范围

2024-07-05 12:42:54 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的文件和输出。我只想得到func1()后面的x的值,作为20I have already referred to this answer。我想知道为什么这样不行?有必要用import globalVar代替from globalVar import *

在球蛋白.py在

#globalVar.py
x=10

趣味1.py

^{pr2}$

在主.py在

from fun1 import *
from globalVar import *

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

输出:

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

Tags: 文件tofrompyimporthavethisprint
2条回答

这不起作用的原因是 fun1()方法调用主.py不返回x ie 20的更新值。 这就是为什么更新的x的作用域只在fun1中,一旦执行结束,该值就会丢失&当您第三次打印x的值时,它只引用全局变量

你可以做些什么使它生效 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。球蛋白.py在

^{pr2}$

3。主.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)

更新答案:

试试这个:

球蛋白.py:

global x
x = 10

fun1.py:

^{pr2}$

主.py:

from fun1 import *
from GlobalVar import *

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

勾选这个,这将根据你的问题给你想要的输出。在

希望这对你有帮助!谢谢你!:)

注意:全局表字典是当前模块的字典(在函数内部,这是定义它的模块,而不是调用它的模块)

相关问题 更多 >