Skip to main content
 首页 » 编程设计

python之如何在Python中拥有一个万能的函数调用,可以调用不同的函数

2025年05月04日8soundcode

我正在尝试用 Python 制作一个基于文本的游戏,但是,如果我不能在一行中做一件事,代码可能很快就会失控。

一、源码:

from sys import exit 
 
prompt = "> " 
inventory = [] 
 
def menu(): 
    while True: 
        print "Enter \"start game\" to start playing." 
        print "Enter \"password\" to skip to the level you want." 
        print "Enter \"exit\" to exit the game." 
        choice = raw_input(prompt) 
        if choice == "start game": 
            shell() 
        elif choice == "password": 
            password() 
        elif choice == "exit": 
            exit(0) 
        else: 
            print "Input invalid. Try again." 
 
def password(): 
    print "Enter a password." 
    password = raw_input(prompt) 
    if password == "go back": 
        print "Going to menu..." 
    else: 
        print "Wrong password. You are trying to cheat by (pointlessly) guess passwords." 
        dead("cheating") 
 
def shell(location="default", item ="nothing"): 
    if location == "default" and item == "nothing": 
        print "Starting game..." 
        # starter_room (disabled until room is actually made) 
    elif location != "default" and item != "nothing": 
        print "You picked up %s." % item 
        inventory.append(item) 
        location() 
    elif location != "default" and item == "nothing": 
        print "You enter the room." 
        location() 
    else: 
        print "Error: Closing game." 
 
def location(): 
    print "Nothing to see here." 
    # Placeholder location so the script won't spout errors. 
 
def dead(reason): 
    print "You died of %s." % reason 
    exit(0) 
 
print "Welcome." 
menu() 

首先,解释一下我的游戏的基本运作方式。 游戏有一个“外壳”(输入完成的地方),它从游戏中的不同“房间”接收信息并向其发送信息,并存储库存。它可以接收两个参数,位置和要添加到库存中的最终项目。但是,第 40-42 行(“shell”中的第一个 elif block )和第 43-45 行(“shell”中的最后一个 elif block )应该返回到该位置所在的任何位置(第 42 和 45 行,将精确的)。我试过 "%s() % location"但这不起作用,它似乎只在打印东西或其他东西时起作用。

有什么办法吗?否则,即使为这款游戏编写引擎也将是一场噩梦。或者我必须制作一个完全不同的引擎,我认为在这种情况下这是一种更好的方法。

对不起,如果我犯了任何错误,第一个问题/帖子。

请您参考如下方法:

elif location != "default" and item != "nothing": 
    print "You picked up %s." % item 
    inventory.append(item) 
    location() 
elif location != "default" and item == "nothing": 
    print "You enter the room." 
    location() 

我猜你想调用一个有它的名字的函数。为此,您需要对定义它的模块或类的引用:

module = some_module # where the function is defined 
function = getattr(module, location) # get the reference to the function 
function() # call the function 

如果函数定义在当前模块中:

function = globals()[location] 
function() # call the function