Skip to main content
 首页 » 编程设计

Python:如何使用循环导入调用另一个文件中的函数

2025年05月04日15youxin

我正在制作一个基于文本的地板游戏,用于学习目的。我希望所有的移动功能都在一个单独的 python 文件中,但我在让它们一起工作时遇到了问题。

我的主游戏名为 floors.py, map 文件为 floormap.py。

我可以从 floormap.py 中的 floormap.py 导入和运行函数,完全没问题。

但我不知道如何在运行floormap.py 函数后返回到floors.py 函数。下面是一个例子。当我运行它时,我在终端中收到以下错误:

NameError: global name 'first_hall_1' is not defined 

我确实使用了这个:

from floormap import first_hall_1 

但我可以找到一种方法让函数在原始文件中再次被调用。

地板.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" 

平面图.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()