You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python跨文件调用变量时用字符串匹配变量名报错如何解决?

错误原因&解决步骤

    1. 模块导入拼写错误
      你在file_2的导入语句写为import gile_1,属于手误拼写错误,修正为import file_1即可。如果你的实际代码中第一个文件命名为words.py,对应修改为import words。
    1. 动态获取模块属性的语法错误
      你通过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(模块对象, 属性名字符串)。
    1. 变量作用域使用错误
      原代码中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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:24:02