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

时间:2010-08-11 05:20:39

标签: 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?')"
    }
}

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

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

我已经看到了许多类似问题的答案,但他们没有处理独特函数的论据 - 更好地说,它们更像是this

3 个答案:

答案 0 :(得分: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.'

答案 1 :(得分:1)

您可以使用代码模块

def eat(target='object'):
    import code
    console = code.InteractiveConsole(locals()) # make a python interpreter with local vars
    if target in inventory:
        console.push("items[target]['on_eat']")
    else:
        print 'You have no ' + target + ' to eat.'

答案 2 :(得分:0)

部分功能的替代方法是编写像这样的项目

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?',))
    }
}

并像这样称呼它

def eat(target='object'):
    if target in inventory:
        func, args = items[target]['on_eat']
        func(*args)
    else:
        print 'You have no ' + target + ' to eat.'

除非您要重新分配

,否则您不需要那些global语句