Python:来自 locals() 的具有定义前缀的随机函数
Python: random function from locals() with defined prefix
我正在从事基于文本的冒险,现在想要 运行 一个随机函数。
所有冒险功能都是 "adv" 后跟一个 3 位数字。
如果我 运行 go() 我回来 :
IndexError: Cannot choose from an empty sequence
这是因为 allAdv 仍然是空的。如果我 运行 go() 在 shell 中逐行运行,但在函数中不起作用。我错过了什么?
import fight
import char
import zoo
import random
#runs a random adventure
def go():
allAdv=[]
for e in list(locals().keys()):
if e[:3]=="adv":
allAdv.append(e)
print(allAdv)
locals()[random.choice(allAdv)]()
#rat attacks out of the sewer
def adv001():
print("All of a sudden an angry rat jumps out of the sewer right beneath your feet. The small, stinky animal aggressivly flashes his teeth.")
fight.report(zoo.rat)
主要是作用域问题,当你在go()
中调用locals()
时,它只会打印出这个函数中定义的局部变量allDev
:
locals().keys() # ['allDev']
但是,如果您在 shell 中逐行键入以下内容,locals()
确实包括 adv001
,因为在这种情况下它们处于同一级别。
def adv001():
print("All of a sudden an angry rat jumps out of the sewer right beneath your feet. The small, stinky animal aggressivly flashes his teeth.")
fight.report(zoo.rat)
allAdv=[]
print locals().keys() # ['adv001', '__builtins__', 'random', '__package__', '__name__', '__doc__']
for e in list(locals().keys()):
if e[:3]=="adv":
allAdv.append(e)
print(allAdv)
locals()[random.choice(allAdv)]()
如果你真的想获取go()
中的那些函数变量,你可以考虑将locals().keys()
更改为globals().keys()