首页 > 解决方案 > 是否可以从字典中调用代码?

问题描述

我正在用 python 制作一个基于文本的游戏,并试图创建一个可能的随机事件字典,如下所示。

events = {
    '1': text:'You find treasure in the chest', code:treasure += 1 
    '2': text:'There is a trap in the chest', code:hp -= 1
}

是否可以在不使用 if 语句或定义的函数的情况下调用链接到事件的代码?

标签: pythondictionary

解决方案


看起来您正在尝试编写匿名函数,而不是引用现有函数。

events = {
    '1': {text:'You find treasure in the chest', code: lambda: treasure += 1},
    '2': {text:'There is a trap in the chest', code: lambda: hp -= 1},
}

现在您可以events['1']['code']()执行该块。


也就是说,考虑一种更面向对象的方法,您可能会创建一个玩家对象并将其传递给动作,从而改变其属性。

from dataclasses import dataclass

@dataclass
class Player:
    hp: int = 10        # or whatever default
    treasure: int = 10  # or whatever default

events = {
    '1': {text:'You find treasure in the chest', code: lambda p: p.treasure += 1}, 
    '2': {text:'There is a trap in the chest', code: lambda p: p.hp -= 1},
}

player = Player()

for event in events.values():
    print(event.text)
    event.code(player)

推荐阅读