简体   繁体   中英

Python: How to Call a function in another file with a circular import

I am making a text-based floor game for learning purposes. I want all of the moving-around functions to be in a separate python file but I am having issues getting them to work together.

I have the main game called floors.py and the map file is floormap.py .

I can import and run functions from floormap.py inside of floors.py perfectly okay.

But I do not know how to return to the floors.py functions after running a floormap.py functions. Here is an example below. When I run this, I get the following error in terminal:

NameError: global name 'first_hall_1' is not defined

I did get this working using:

from floormap import first_hall_1

But I could find a way to get the functions to once again be called in the original file.

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()

You need to qualify first_hall_1 with the module name floormap .

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()  # <-----

Same for the walkin_hall() call:

def first_hall_1():
    print "You are in front of the door again. It is locked."
    floors.walkin_hall()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM