2014-04-06 4 views
1

알고 싶습니다. 조건문의 목록에서 임의로 가져온 함수를 어떻게 테스트 할 수 있습니까? 다음은 몇 가지 예제 코드입니다. 코드가 무엇을 인쇄해야하는지 무시하십시오.파이썬의 목록에서 호출 된 함수 테스트

import random, time 
def biomeLand(): 
    print "Biome: Land" 

def biomeOcean(): 
    print "Biome: Ocean" 

def biomeDesert(): 
    print "Biome: Desert" 

def biomeForest(): 
    print "Biome: Forest" 

def biomeRiver(): 
    print "Biome: River" 

biomes = [biomeLand, biomeOcean, biomeDesert, biomeForest, 
      biomeRiver] 

def run(): 
    while True: 
     selected_biome = random.choice(biomes)() 
     time.sleep(0.5) 
run() 

다시 말해서 프로그램이 조건부 명령문에서 특정 함수가 목록에서 호출 될 때 테스트 할 수 있습니까?

답변

1

당신은 다른 변수처럼 그들을 일치시킬 수 있습니다 :

def foo(): 
    print "foo" 

def bar(): 
    print "bar" 

first = foo 

print (first == bar) # prints "False" 
print (first == foo) # prints "True" 

을 그래서 예를 들어 당신이 단지 같은 것을 가질 수 있습니다 어쩌면

if selected_biome == biomeLand: 
    # do something 
2

:

def run(): 
    while True: 
     selected_biome = random.choice(biomes) 
     selected_biome() 
     if selected_biome == biomeLand: 
      print "biomeLand Selected" 
     time.sleep(0.5) 
run()