【发布时间】:2016-01-16 16:33:39
【问题描述】:
我正在制作一个基于文本的地板游戏,用于学习目的。我希望所有的移动函数都在一个单独的 python 文件中,但是我在让它们一起工作时遇到了问题。
我的主游戏名为floors.py,地图文件为floormap.py。
我可以从floormap.py 内部的floors.py 导入和运行函数,完全没问题。
但我不知道在运行floormap.py 函数后如何返回floors.pyfunctions。下面是一个例子。当我运行它时,我在终端中收到以下错误:
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.py 导入 floormap 并调用 floormap 函数,但 不要 让 floormap.py 也导入 floor 并调用 floormap 函数。循环进口是合法的,但它们可能会带来痛苦。
标签: python function python-import