-1
我想访问变量使用字符串从一个文件到其他文件中的类。如何使用其他作用域的字符串访问变量?
这是我的代码。
文件a.py
:
aa = 12
m = test('aa')
文件class.py
:
class test:
def __init__(self,string):
try:
self.variable = globals()[string]
except KeyError:
print('there is no variable named ' + string)
以上test.py
代码返回序列串 '没有名为blrblr变量'。我认为如果Python有词法范围,test()
第一次被调用时的范围应该与'aa'
有相同的范围,但它不会。我怎样才能解决这个问题?
您认为'class.py'会搜索哪些'globals'?这就是为什么你基本上不会在生产代码中看到像'globals()'(或'locals()'等)的东西。你几乎肯定有一个[XY问题](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 – TigerhawkT3
'class test'的词法范围是'class.py',而不是'a.py',所以它不会在'a.py'中看到变量。 – tdelaney
题外话:因为“class”是一个Python关键字,所以你可能永远不会想要命名一个要导入的模块'class.py',因为你不能执行'import class'。 – martineau