1

我正在进行基于文本的冒险,现在想运行一个随机函数。所有冒险功能都是“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)
4

1 回答 1

0

这主要是由于范围问题,当您调用locals()in时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()

于 2015-02-13T13:13:03.183 回答