Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.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_Scope - Fatal编程技术网

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
动态导入它。嗯,我误解了词法范围的定义。非常感谢你!