【发布时间】:2019-06-19 06:46:53
【问题描述】:
我的目录结构如下:
my-game/
__init__.py
logic/
__init__.py
game.py
player.py
game.py 和 player.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