全局变量在模块中的作用域 [英] Global variables scope in modules

查看:48
本文介绍了全局变量在模块中的作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的文件和输出.我要做的就是在func1()之后将x的值获取为20. 我已经提到了这个答案.我想知道为什么这不起作用?是否有必要使用import globalVar代替from globalVar import *

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

#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)

输出:

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

推荐答案

更新后的答案:

尝试一下:

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)

这篇关于全局变量在模块中的作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆