【问题标题】:Using variables from other Python file使用其他 Python 文件中的变量
【发布时间】:2018-10-25 10:58:31
【问题描述】:

我正在用 Python 制作一个小游戏,对此我还是很陌生。我正在尝试使用导入访问另一个文件中的变量,但它一直在说

AttributeError: 模块 'core temp' 没有属性 'ct'

这是我正在尝试运行的代码:

elif cmd == "temp":
    if core.ct < 2000:
      print(colored("Core temperature: "+core.ct+"°C", "green"))
    elif core.ct < 4000:
      print(colored("Core temperature: "+core.ct+"°C", "yellow"))
    elif core.ct >= 3000:
      print(colored("Core temperature: "+core.ct+"°C", "red"))

我正在像这样导入 coretemp:import coretemp as core

这是 coretemp.py 中的代码:

from time import sleep as wait
import coolant as c

ct = 10

while True:
    if c.coolactive == False:
        ct = ct + 1
        wait(.3)
    else:
        ct = ct - 1
        wait(1)

我被这个问题困扰很久了!

PS:抱歉,如果格式不正确,我在移动设备上,这很难。

【问题讨论】:

  • 那个代码在“coolant”里吗?
  • 第一块代码在main,第二块在coretemp
  • 您的主脚本的名称是什么?确保您没有尝试在任何地方导入主脚本,因为这可能会导致以下问题:如果脚本是 coolant.py,那么在 coretemp 中的导入将导入脚本的第二个副本,该副本将尝试访问 @ 987654326@ 模块在执行之前。这将给出您所看到的错误。
  • @Duncan 主文件是 main.py

标签: python-3.x repl.it


【解决方案1】:

如果coolant 模块也导入coretemp,我可以看到您会收到此错误的唯一方法。 (顺便说一句,我假设core temp 中的空格是复制/粘贴错误)

如果coolant 导入coretemp,它将访问模块的副本,因为它在coretemp 导入coolant 时存在。这意味着 ct 尚未定义。

请注意,main 中的导入永远不会完成,因为coretemp.py 在顶层包含一个无限循环:main 将永远等待它正在导入的模块完成执行。

【讨论】:

  • 是的,昨晚我稍微调整了代码,并意识到 while True 循环会停止一切。但是,我需要一个无限循环来增加或减少 ct。有没有办法在不暂停其他所有内容的情况下做到这一点?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-29
  • 1970-01-01
  • 2019-10-24
  • 2017-03-09
  • 2016-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多