[英]How do I make a function to accept an argument that is another function?
我的问题似乎令人困惑,但这是我想到的唯一方法。 对于任何混乱,我深表歉意,我将尽力解释。
基本上,我想做的是在游戏中提供一个简单的退出功能,询问“您要退出吗?”。 如果用户输入否,则将其返回到其所在的功能。
这是我尝试执行的操作,但是似乎只是循环回到“ bear_room()”函数。
def bear_room():
print "You are greeted by a bear"
next = raw_input()
if next == 'fight':
print 'You tried to fight a bear. You died'
elif next == 'exit':
exit_game(bear_room())
else:
print 'I did not understand that!'
bear_room()
def exit_game(stage):
print '\033[31m Are you sure you want to exit? \033[0m'
con_ext = raw_input(">")
if con_ext == 'yes':
exit()
elif con_ext == 'no':
stage
else:
print 'Please type ''yes'' or ''no'
exit_game()
你几乎明白了; 您只需在将其作为参数传递时不调用bear_room
:
elif next == 'exit':
exit_game(bear_room)
相反,您需要将stage
作为函数调用:
elif con_ext == 'no':
stage()
您需要了解传递函数和调用函数之间的区别。
在这里,您将对raw_input
函数的引用复制到next
变量中,而无需实际执行它。 您可能要在raw_input
添加括号()
:
next = raw_input
在这里,您将递归地再次调用bear_room()
,而不是exit_game
它的引用传递给exit_game
函数。 您可能要删除括号()
到bear_room
:
elif next == 'exit':
exit_game(bear_room())
同样,提及不带括号的函数不会执行该函数,因此您也想在此处添加这些函数:
elif con_ext == 'no':
stage
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.