Python:来自locals()的随机函数,带有已定义的前缀

时间:2015-02-13 12:42:22

标签: python python-3.x locals

我正在进行基于文本的冒险,现在想要运行一个随机函数。 所有冒险功能都是" adv"后跟一个3位数字 如果我跑go()我会回来:

IndexError: Cannot choose from an empty sequence

这是因为allAdv仍为空。如果我在shell中逐行运行go()它可以工作但不在函数中。我错过了什么?

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)

1 个答案:

答案 0 :(得分:0)

这主要是由于范围问题,当您在locals()中调用go()时,它只打印出此函数中定义的局部变量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()