跨模块动态访问全局变量

时间:2021-04-25 23:38:04

Using something from on another page on this site, I've managed to create global variables that are accessible across modules by doing something along the lines of--

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

Mod1.py--

def init():
    global testVar

mod2.py--

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

How, though, in mod2.py, can I dynamically access global variables in mod1? Something like--

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

nameOfVarThatIWant = 'testVar'
print(mod1.globals()[nameOfVarThatIWant])

1 个解决方案

#1


0  

Answer based on the two very helpful comments above--

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

getattr(mod1, nameOfVarThatIWant)

or built-in function in mod1 that uses globals()

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

#1


0  

Answer based on the two very helpful comments above--

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

getattr(mod1, nameOfVarThatIWant)

or built-in function in mod1 that uses globals()

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