【问题标题】:Python: random function from locals() with defined prefixPython:来自locals()的随机函数,具有定义的前缀
【发布时间】:2015-02-13 12:42:22
【问题描述】:

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

【问题讨论】:

  • “在 shell 中逐行运行 go()”是什么意思?
  • 我进入 shell 并以相同的顺序复制/粘贴 go() 函数中的每一行(以及作为一个块的 for 循环)并尝试了它

标签: python python-3.x locals


【解决方案1】:

主要是作用域问题,当你在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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多