Python3 中的循环导入

Cyclic import in Python3

我的目录结构如下:

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'

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

$ 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.

在这种情况下,我得到了一个不同的错误。例如,当 运行ning 来自 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/ 目录 运行ning 时,我得到了类似的错误。

我看了 this post 但不明白我哪里错了。

您在代码中进行了循环导入尝试将其从导入中删除 访问这个 link 你可以找到一些关于循环导入的其他信息:Remove python circular import