Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.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

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 - Fatal编程技术网

Python:如何使用字符串访问另一个模块中的变量

Python:如何使用字符串访问另一个模块中的变量,python,variables,Python,Variables,假设我有一个名为Test1.py的模块,其中有变量 something = 10 apple = 5 (注意:我事先不知道这些变量,它们将从另一个模块动态添加)。那么,在给定字符串的不同的模块中如何使用这些变量呢。例如,我想使用字符串“apple”从该模块访问apple变量。一般来说,是这样的 AnotherModule.py import Test1 var = input('Variable: ') print(Test1.var) 显然,这是可行的,如果我把输入设为“apple”

假设我有一个名为
Test1.py
的模块,其中有变量

something = 10

apple = 5
(注意:我事先不知道这些变量,它们将从另一个模块动态添加)。那么,在给定字符串的不同的模块中如何使用这些变量呢。例如,我想使用字符串“apple”从该模块访问
apple
变量。一般来说,是这样的

AnotherModule.py

import Test1

var = input('Variable: ')
print(Test1.var)

显然,这是可行的,如果我把输入设为“apple”,我希望结果是5。因为另一个模块中的苹果是5。你可以使用
getattr

getattr(Test1, var)
getattr(Test1,var)