Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按名称从另一个模块访问变量_Python_Variables_Dynamic_Global Variables - Fatal编程技术网

Python 按名称从另一个模块访问变量

Python 按名称从另一个模块访问变量,python,variables,dynamic,global-variables,Python,Variables,Dynamic,Global Variables,我有一个模块a.py,其中声明了所需的所有变量: dog_name = '' dog_breed = '' cat_name = '' cat_breed = '' # ..... 我有一个导入a的文件B.py。我知道如何访问在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 f

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

dog_name = ''
dog_breed = ''
cat_name = ''
cat_breed = ''
# .....
我有一个导入a的文件B.py。我知道如何访问在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

有什么方法可以实现这一点吗?

您可以对模块使用
getattr

import A

getattr(A, 'dog_name')
# ''
setattr
,以及:

setattr(A, 'dog_name', 'fido')
getattr(A, 'dog_name')
# 'fido'

你做过什么调查吗?还有,请看一下。是的,我看了。我无法获得这些值。A.x给我变量不可用错误。我无法分辨x.Super的值。非常感谢你。