Python 如何使用其他作用域中的字符串访问变量?
我想使用字符串从一个文件访问另一个文件中的类 这是我的密码 文件Python 如何使用其他作用域中的字符串访问变量?,python,scope,Python,Scope,我想使用字符串从一个文件访问另一个文件中的类 这是我的密码 文件a.py: aa = 12 m = test('aa') class test: def __init__(self,string): try: self.variable = globals()[string] except KeyError: print('there is no variable named ' + string) 文件
a.py
:
aa = 12
m = test('aa')
class test:
def __init__(self,string):
try:
self.variable = globals()[string]
except KeyError:
print('there is no variable named ' + string)
文件class.py
:
aa = 12
m = test('aa')
class test:
def __init__(self,string):
try:
self.variable = globals()[string]
except KeyError:
print('there is no variable named ' + string)
上面的test.py
code返回序列字符串“没有名为blrblr的变量”。我认为,如果Python有词法作用域,那么调用test()
class first时的作用域应该与'aa'
具有相同的作用域,但它没有。如何修复此问题?globals()
返回当前模块的属性字典。访问不同文件中代码的常用方法是使用import
。比如说
import a
现在,您可以在代码中直接从a.py
访问变量:
print(a.aa)
虽然有办法做到这一点,但不建议尝试使用字符串作为变量名。相反,您应该使用诸如字典之类的数据结构。在
globals
中,您认为class.py
会搜索什么?这就是为什么在生产代码中基本上看不到像globals()
(或locals()
)之类的东西。你几乎肯定有一个。类测试的词法范围是class.py
,而不是a.py
,因此它不会在a.py
中看到变量。离题:人们可能永远不会想命名要导入的模块class.py
,因为“class”之后你将无法执行import class
是Python关键字。类测试
将无法看到a.py
,除非它导入该模块。如果要动态解析变量,可以在a.py
中执行m=test(globals()['aa'])
。否则,您需要将模块传递到test
-或模块的名称,并让test
动态导入它。嗯,我误解了词法范围的定义。非常感谢你!