python - 是否可以从字典中调用代码?
问题描述
我正在用 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 语句或定义的函数的情况下调用链接到事件的代码?
解决方案
看起来您正在尝试编写匿名函数,而不是引用现有函数。
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)
推荐阅读
- c# - IronPython:从 c# 启动 .py 脚本时出错
- android - `.db` 文件在调用 Room.createFromAsset("initialData.db") 时应该采用什么格式?
- python - 无论操作系统如何,如何在 python 中连接 oracle 数据库
- elasticsearch - 重复的 ElasticSearch 文档
- kubernetes - kubenrates (k8s) nd POD OOMKILLED 在非工作时间且没有内存峰值
- python - 如何在北极立体投影中添加更多经度/纬度线
- git - 如何保存或“隐藏”最后一次提交?
- flutter - 如何从外部父小部件或另一个未来构建器访问未来构建器内部的功能
- machine-learning - RuntimeError:输入类型(torch.cuda.FloatTensor)和权重类型(torch.FloatTensor)应该相同
- javascript - 两种形式,两种输入...但只有一种输出,使用 Javascript + web3