跨模块动态访问全局变量

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

在本网站的另一个页面上使用了一些东西,我设法创建了可以跨模块访问的全局变量,通过做一些事情 -

Mod1.py--

def init():
    global testVar

mod2.py--

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

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

nameOfVarThatIWant = 'testVar'
print(mod1.globals()[nameOfVarThatIWant])
python
1个回答
0
投票

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

getattr(mod1, nameOfVarThatIWant)

或使用globals()的mod1中的内置函数

© www.soinside.com 2019 - 2024. All rights reserved.