跨模块动态访问全局变量

时间:2018-03-05 19:10:20

标签: python

使用本网站上其他页面上的内容,我设法创建了可通过以下方式执行操作的模块之间可访问的全局变量 -

Mod1.py -

def init():
    global testVar

mod2.py -

import mod1
mod1.init()
print(mod1.testVar)

但是,如果在mod2.py中,我可以动态访问mod1中的全局变量吗?像 -

这样的东西
nameOfVarThatIWant = 'testVar'
print(mod1.globals()[nameOfVarThatIWant])

1 个答案:

答案 0 :(得分:0)

根据上面两条非常有用的评论回答 -

getattr(mod1, nameOfVarThatIWant)

或mod1中使用globals()

的内置函数