2010-08-11 5 views
5

나는 선수가 뭔가 먹고하려고 할 때 실행이 코드가 있습니다국가 번호, 파이썬

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

을 exec() 나 eval()과 같은 어리석은 짓을하지 않고 아이템을 호출하는 유효한 방법이 있습니까? 그렇지 않은 경우, 예로서 대체 서식을 사용하는 것도 좋습니다.

[item] [everyitems] [ 'on_eat] 값은 문자열이 아니었지만 코드가 실행되는 즉시 모든 항목에 대해 on_eat를 실행했습니다.

내가 비슷한 질문에 많은 답변을 봐 왔지만, 기능은 더 나은 것을 넣어 unique- 위해 그들이 인수 거래를하지 않는, 그들은 더 this 같았

당신은 partial로 기능과 함수 인수를 저장할 수

답변

6

:

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.' 
+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 문을 필요로하지 않는다; 그것은 작동합니다. 글쎄,이게 말이 되겠지, 너/누군가가 스피드/CPU/계단 현명한 방법을 알려줄 수 있니? 또한 items [blah] [ 'on_eat'] 값이 덜/정상적인 함수 호출 일 때 항목이 정의되고 나면 부분 데이터가 우연히 실행되지 않는 이유는 무엇입니까? –

+0

부분이 실제로 항목 *의 on_eat 요소에서 만들어 질 때 partial이 함수를 * 호출 *하지 않기 때문에. 함수 호출은 호출 할 함수와 호출 할 인수를 모두 캡처합니다. 이 함수는 partial에 접근 할 때 호출되고()로 호출됩니다. 이것을 시도하십시오 : z = 부분 (분, 2, 4, 6) 아무 일도 일어나지 않습니다. 이제 z : z()를 호출합니다. 대답 2가 반환됩니다. 부분이 만들어 질 때 min이 호출되지 않았습니다. 부분을 ​​z()로 호출 할 때만 호출되었습니다. Speedwise, 원래 함수를 호출하는 것과 거의 비슷해야합니다. – PaulMcG

+0

감사합니다. 또한, 내가 인쇄하고, current_room을 변경하고, normal_eat를 호출하고, 다시 인쇄하고, 사용자 스피커를 폭발시키는 아이템 [단테의 지옥의 마법의 수송 음식] [ 'on_eat']을 사용하여 한 번에 여러 가지 일을하고 싶다면 어떻게해야할까요? 이 모든 작업을 수행하는 별도의 함수를 만들어야한다고 가정합니다. –

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.' 
+0

죄송합니다. 객체 – user250418

+2

다음에 닫는 따옴표를 놓친 후 잘 편집하십시오! – aaronasterling

0

을 사용할 수 있습니다 당신이 그들에게 이상한

관련 문제