python - 在没有exec/eval,python的字符串中调用代码

标签 python reference eval exec

当玩家尝试吃东西时,我将执行以下代码:

def eat(target='object'):
    global current_room
    global locations
    global inventory
    if target in inventory:
        items[target]['on_eat'] #This is showing no results.
    else:
        print 'You have no ' + target + ' to eat.'

和此代码的项目(修剪)
items = {
'strawberry': {
    'weight': 1,
    'text': 'The strawberry is red',
    'on_eat': "normal_eat('strawberry', 'pretty good, but not as sweet as you expected')"
    },
'trees': {
    'weight': 50,
    'text': 'The trees are tall with large, leaf filled branches blocking out a majority of sunlight.',
    'on_eat': "forcesay('Eating trees? What the hell is your problem?')"
    }
}

是否有一种有效的方法来调用item [whatever] ['on_eat'],而无需执行exec()或eval()之类的愚蠢行为?如果不是这样,则也将理解替代格式作为示例。

在此之前,items [everyitems] ['on_eat']的值不是字符串,而是在代码运行后立即为每个项目执行on_eat。

我已经看到了许多类似问题的答案,但是它们不处理唯一函数的参数-更好的说,它们更像this

最佳答案

您可以将函数和函数参数存储为partial:

from functools import partial

items = { 
'strawberry': { 
    'weight': 1, 
    'text': 'The strawberry is red', 
    'on_eat': partial(normal_eat, 'strawberry', 'pretty good, but not as sweet as you expected') 
    }, 
'trees': { 
    'weight': 50, 
    'text': 'The trees are tall with large, leaf filled branches blocking out a majority of sunlight.', 
    'on_eat': partial(forcesay, 'Eating trees? What the hell is your problem?')
    } 

def eat(target='object'):  
    # those globals are probably not necessary
    if target in inventory:  
        items[target]['on_eat']()  #Add ()'s to call the partial
    else:  
        print 'You have no ' + target + ' to eat.'

关于python - 在没有exec/eval,python的字符串中调用代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3455490/

相关文章:

python - eval() 函数如何改变字典?

python结合map()的两种逻辑

python - 将 Pyomo 与 PyInstaller 一起使用

python - 如何通过引用传递变量?

string - 使变量引用其自己的字符串内容

javascript - eval 不适用于变量

python - 发生此错误后如何安装 aggdraw?

python - 编码斯洛伐克语字母,如 : á š Č é

C# 项目看不到 Excel COM Reference

jquery - 如何使用 jQuery 评估变量