【问题标题】:Cyclic import in Python3Python3中的循环导入
【发布时间】:2019-06-19 06:46:53
【问题描述】:

我的目录结构如下:

my-game/
  __init__.py
  logic/
    __init__.py
    game.py
    player.py

game.pyplayer.py 相互之间存在导入依赖(循环导入)。

game.py 有如下定义。

from logic.player import RandomPlayer, InteractivePlayer

T = 8

class Game:
  def __init__(self, p1, p2)
    ...

# some other things

if __name__ == '__main__':
  p1 = RandomPlayer()
  p2 = InteractivePlayer()
  g = Game(p1, p2)
  ...

player.py如下:

from logic.game import T

class Player:
  def __init__(self):
    ...

class RandomPlayer(Player):
  def __init__(self):
    ...

class InteractivePlayer(Player):
  def __init__(self):
    ...

我正在尝试从logic/ 目录运行游戏,但出现以下错误。

$ python3 game.py
Traceback (most recent call last):
  File "game.py", line 2, in <module>
    from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'

然后我尝试从更高的目录 (my-game/) 运行 game.py

$ python3 logic/game.py
Traceback (most recent call last):
  File "logic/game.py", line 2, in <module>
    from logic.player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named 'logic'

我做错了什么?如何使这些循环导入起作用?

我也试过在player.py中使用这个导入

from .game import T

并使用

from .player import RandomPlayer, InteractivePlayer

game.py.

在这种情况下,我得到一个不同的错误。例如,从my-game/ 运行时,

$ python3 logic/game.py
Traceback (most recent call last):
  File "logic/game.py", line 2, in <module>
    from .player import RandomPlayer, InteractivePlayer
ModuleNotFoundError: No module named '__main__.player'; '__main__' is not a package

logic/ 目录运行时出现类似错误。

我查看了this 的帖子,但不明白我哪里出错了。

【问题讨论】:

    标签: python-3.x python-import python-module


    【解决方案1】:

    您在代码中进行了循环导入尝试将其从导入中删除 访问此链接,您可以找到有关循环导入的其他信息:Remove python circular import

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-05
      • 2017-01-19
      • 2019-05-02
      • 2010-10-19
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      相关资源
      最近更新 更多