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

如何在Python导入文件中使用其他文件定义的变量?

解决跨模块调用变量的问题

你的代码有两个问题导致无法调用rep_date变量:

  • 导入的模块名称错误,test2.py里应该导入test1而非importFile2
  • 变量属于test1模块的命名空间,不能直接全局调用,需要通过模块引用或显式导入

修正方案一:通过模块名访问变量

修改test2.py代码如下:

#---Script in the file2 called test2.py-----------------------------------------------------------------
import test1
print("Date entered: " + test1.rep_date)

修正方案二:直接导入指定变量

如果不想每次都写模块名,可以单独导入rep_date:

#---Script in the file2 called test2.py-----------------------------------------------------------------
from test1 import rep_date
print("Date entered: " + rep_date)

注意:运行test2.py时,test1.py里的input()代码会被执行,所以会先弹出输入提示,这是模块导入时的正常行为。

内容的提问来源于stack exchange,提问作者Joao Beca

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 01:09:52