Python跨文件调用变量时用字符串匹配变量名报错如何解决?
错误原因&解决步骤
- 模块导入拼写错误
你在file_2的导入语句写为import gile_1,属于手误拼写错误,修正为import file_1即可。如果你的实际代码中第一个文件命名为words.py,对应修改为import words。
- 模块导入拼写错误
- 动态获取模块属性的语法错误
你通过random.choice(file_1.type_Of_word)拿到的type_of_word_choice是字符串类型的变量(比如值为'movies'/'animals'),不能直接用file_1.type_Of_word_choice的点语法访问:点语法后面会被识别为固定的属性名,Python会去file_1模块里找名为type_Of_word_choice的属性,这个属性显然不存在,所以抛出AttributeError。
要通过字符串类型的变量动态获取模块属性,需要使用Python内置的getattr()方法,用法为getattr(模块对象, 属性名字符串)。
- 动态获取模块属性的语法错误
- 变量作用域使用错误
原代码中file_1.type_Of_word_choice的写法混淆了局部变量和模块属性:type_of_word_choice是你在get_word函数内定义的局部变量,不属于file_1模块的属性,不需要加file_1.前缀。
- 变量作用域使用错误
修正后的file_2代码
import random import file_1 # 如果你实际文件名为words.py,这里改为 import words word = None def get_word(): type_of_word_choice = random.choice(file_1.type_Of_word) global word # 用getattr动态获取对应列表 target_list = getattr(file_1, type_of_word_choice) word = random.choice(target_list) print(word)
内容的提问来源于stack exchange,提问作者SkyWalker
相关产品推荐
相关产品推荐

