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

mas*_*man 5 python eval reference 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.'
Run Code Online (Sandbox Code Playgroud)

和这个项目的代码(修剪)

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?')"
    }
}
Run Code Online (Sandbox Code Playgroud)

是否有一种有效的方式来调用项目[无论如何] ['on_eat']而不做像exec()或eval()那样愚蠢的事情?如果没有,作为示例的替代格式也将被理解.

在此之前,[everyitems] ['on_eat']项的值不是字符串,但是一旦代码运行,它就会为每个项执行on_eat.

我已经看到了类似问题的许多答案,但他们没有处理独特函数的论证 - 更好地说,他们更喜欢这个

Pau*_*McG 6

您可以将函数和函数参数存储为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.'
Run Code Online (Sandbox Code Playgroud)