Python: 如何通过循环导入调用另一个文件中的函数
Python: How to Call a function in another file with a circular import
我正在制作一个基于文本的地板游戏以供学习之用。我希望所有的移动功能都在一个单独的 python 文件中,但我在让它们一起工作时遇到了问题。
我有一个名为 floors.py
的主游戏,地图文件是 floormap.py
。
我可以从 floors.py
内部的 floormap.py
导入和 运行 函数,完全没问题。
但我不知道如何在 运行 宁一个 floormap.py
函数之后 return 到 floors.py
函数。下面是一个例子。当我 运行 这样做时,我在终端中收到以下错误:
NameError: global name 'first_hall_1' is not defined
我确实使用了这个:
from floormap import first_hall_1
但我可以找到一种方法让函数在原始文件中再次被调用。
Floors.py:
import floormap
def first_hall_object():
grab = raw_input("Enter Command > ")
backward = ['back', 'Back', 'Backward', 'backward']
if any (s in grab for s in backward):
first_hall_1()
def walkin_hall():
print "whatever"
floormap.py:
import floors
def first_hall_1():
print "You are in front of the door again. It is locked."
walkin_hall()
您需要使用模块名称 floormap
来限定 first_hall_1
。
def first_hall_object():
grab = raw_input("Enter Command > ")
backward = ['back', 'Back', 'Backward', 'backward']
if any (s in grab for s in backward):
floormap.first_hall_1() # <-----
walkin_hall()
调用相同:
def first_hall_1():
print "You are in front of the door again. It is locked."
floors.walkin_hall()
我正在制作一个基于文本的地板游戏以供学习之用。我希望所有的移动功能都在一个单独的 python 文件中,但我在让它们一起工作时遇到了问题。
我有一个名为 floors.py
的主游戏,地图文件是 floormap.py
。
我可以从 floors.py
内部的 floormap.py
导入和 运行 函数,完全没问题。
但我不知道如何在 运行 宁一个 floormap.py
函数之后 return 到 floors.py
函数。下面是一个例子。当我 运行 这样做时,我在终端中收到以下错误:
NameError: global name 'first_hall_1' is not defined
我确实使用了这个:
from floormap import first_hall_1
但我可以找到一种方法让函数在原始文件中再次被调用。
Floors.py:
import floormap
def first_hall_object():
grab = raw_input("Enter Command > ")
backward = ['back', 'Back', 'Backward', 'backward']
if any (s in grab for s in backward):
first_hall_1()
def walkin_hall():
print "whatever"
floormap.py:
import floors
def first_hall_1():
print "You are in front of the door again. It is locked."
walkin_hall()
您需要使用模块名称 floormap
来限定 first_hall_1
。
def first_hall_object():
grab = raw_input("Enter Command > ")
backward = ['back', 'Back', 'Backward', 'backward']
if any (s in grab for s in backward):
floormap.first_hall_1() # <-----
walkin_hall()
调用相同:
def first_hall_1():
print "You are in front of the door again. It is locked."
floors.walkin_hall()