2013-09-06 2 views
2

메서드를 함수 매개 변수로 전달할 수 있습니까? 하고 사용하는 방법을, 나는 시도하고 사용하는 난 그냥 반복적으로 다른 정규 표현식 메소드를 호출 할 수있는 기능을 만들기로 결정 정규 표현식 학습에서메서드를 함수 매개 변수로 전달

:

def finder (regex, query, method): 
     compiled = re.compile(regex) 
     if compiled.method(query) is True: 
      print "We have some sort of match!" 
     else: 
      print "We do not have a match..." 

나는 그것을 밖으로 시도, atrribute 오류가 발생합니다. '_sre.SRE_pattern'에는 컴파일시 호출 가능해야하는 세 번째 매개 변수로 "search"를 전달하더라도 'method'속성이 없습니다. 내가 잘못하고 있거나 완전히 이해하지 못한 것은 무엇인가?

답변

3

문자열로 패스 method 및 사용 getattr : 또한

def finder (regex, query, method): 
    compiled = re.compile(regex) 
    if getattr(compiled, method)(query): 
     print "We have some sort of match!" 
    else: 
     print "We do not have a match..." 

finder(regex, query, "search") 

,

if condition 

대신

if condition is True 

compiled.method(query) 일치하는 항목을 발견하면, 그것은을 반환하기 때문에 사용 일치 개체가 아니라 True입니다.

+0

getattr()에 대한 기본 반환 값 (세 번째 인수)을 여기에 추가하면 유용 할 수도 있습니다. 전달 된 문자열이'compiled '의 속성과 일치하지 않는 경우를 대비하여. 그렇지 않으면,'AttributeError' – samstav

관련 문제