通过名称访问另一个模块的变量

时间:2017-07-19 20:27:06

标签: python variables dynamic global-variables

我有一个模块A.py,我在其中声明了所需的所有变量:

dog_name = ''
dog_breed = ''
cat_name = ''
cat_breed = ''
# .....

我有一个文件B.py,我导入A.我知道如何访问我在A:

中定义的变量
import A 

A.dog_name = 'gooddog' # I am able to use A in file B
A.cat_name = 'goodcat'

print(A.dog_name) # this is working fine

但我希望用户输入他想要访问的变量的名称,例如' cat_name'或者' dog_name'。

x = input('Which variable do you want to read') # could be cat_name or dog_name

# This fails:
print(A.x) # where x should resolve to cat_name and print the value as goodcat

有什么方法可以实现这个目标吗?

1 个答案:

答案 0 :(得分:1)

您可以将getattr与模块一起使用:

import A

getattr(A, 'dog_name')
# ''

setattr,以及:

setattr(A, 'dog_name', 'fido')
getattr(A, 'dog_name')
# 'fido'
相关问题