gpt4 book ai didi

python - 来自 dict 的可变函数调用

转载 作者:太空宇宙 更新时间:2023-11-03 12:44:25 26 4
gpt4 key购买 nike

我是一个相对较新的人,拥有相当多的经验,我正在尝试制作基于文本的冒险,我正在制作一个战斗系统并希望拥有具有不同能力的敌人。我不是每次都为不同的敌人重新战斗,而是尝试为每个敌人使用可互换的词典。我的目标是创建一个函数调用,该函数调用会根据战斗中的敌人而变化,而不会进入对象。我在下面有一个例子,想知道是否有办法做类似的事情。

wolf = {'ability': 'bite'}
bear = {'ability': 'claw'}
enemy = {}

def claw():
print('stuff')

def bite():
print('different stuff')

def use_ability():
enemy = wolf
enemy['ability']()

use_ability()

最佳答案

在 python 中,函数是一等对象。您可以将它们用作字典中的值。

wolf = {'ability': bite}
bear = {'ability': claw}

但是要小心,因为 python 中没有前向引用。因此,请确保先定义函数,然后再将它们分配给字典。

def claw():
print('stuff')

def bite():
print('different stuff')

wolf = {'ability': bite}
bear = {'ability': claw}

def use_ability():
enemy = wolf
enemy['ability']()

use_ability()

关于python - 来自 dict 的可变函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44049468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com