全局变量范围在模块中

问题描述 投票:2回答:2

以下是我的文件和输出。我想做的就是在x之后获得func1()的价值为20I have already referred to this answer。我想知道为什么这不起作用?是否有必要使用import globalVar而不是from globalVar import *

global var.朋友

#globalVar.py
x=10

妇女1.朋友

from globalVar import *

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

卖弄.朋友

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
python scope global-variables
2个回答
1
投票

更新答案:

试试这个:

global var.朋友:

global x
x = 10

妇女1.朋友:

import GlobalVar

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

卖弄.朋友:

from fun1 import *
from GlobalVar import *

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

检查这一点,这将根据您的问题为您提供所需的输出。

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

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


0
投票

这不起作用的原因是main.py中的fun1()方法调用不返回x即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.global var.朋友

x=10

3.卖弄.朋友

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)
© www.soinside.com 2019 - 2024. All rights reserved.