2013-11-22 12 views
-2

에 저장되어있는 메소드를 호출하는 방법 당신은 무엇을 시도하고, //TypeError: 'unicode' object is not callable내가 얻을이 유니 코드 데이터 callable.The 오류를 만드는 방법을 이름이 다음 코드에서 변수

def test(test_config): 
    for i in test_config: 
     print i.header //prints func1 
     print type(i.header) // prints unicode 
     try: 
     #i.header()//TypeError: 'unicode' object is not callable 
     func = globals()[i.header] 
     print func # found it 
     func() 
     except AttributeError: 
     logging.error("Method %s not implemented"%(i.header)) 

    def func1(): 
     print "In func1" 

test(u'func1')  
+0

당신이 그 * 이름은'i.header' 변수에 의해 참조 * 메서드를 호출하려고 여부는 분명이 방법은? – shx2

+0

업데이트 된 질문 – Rajeev

+1

을 참조하십시오. 전화를 걸 때 무엇을 기대합니까? –

답변

3

당신이 문자열을 사용하여 호출 할 함수의 딕셔너리 만들기 : 클래스 사용

def test(test_config): 
    for i in test_config: 
     print i.header //prints func1 
     print type(i.header) 
     try: 
     methods[i.header]() 
     except (AtributeError, TypeError): 
     logging.error("Method %s not implemented"%(i.header)) 

def func1(): 
    print "In func1" 
def func2(): 
    print "In func2" 

methods = {u'func1':func1, u'func2':func2} #Methods that you want to call 

을 :

class A: 
    def test(self, test_config): 
     try: 
      getattr(self, i.header)() 
     except AtributeError: 
      logging.error("Method %s not implemented"%(i.header)) 

    def func1(self): 
     print "In func1" 
x = A() 
x.test(pass_something_here) 
+0

사전을 사용하지 않고 다른 방법이 있습니까? – Rajeev

+1

+1 명시 적 사전은 전역 검색()을 우선해야합니다. 실수로 "테스트"라는 헤더가있는 것을 발견하고 싶지는 않습니다. –

+0

@Rajeev 그런 다음 클래스를 사용하면'getattr'을 사용하여 메소드를 호출 할 수 있습니다. –

3

입니다 할일은 i.header 변수에 의해 참조 된 함수를 찾아서 호출하는 것입니다. (제목이 혼란 스럽기 때문에 실제 unicode 인스턴스를 호출 가능하게 만들고 싶다는 인상을줍니다.)

이 사용하여 수행 할 수있는 globals() :

func = globals()[i.header] 
print func # found it 
func() # call it 
+1

아이디어가'i.header'에 함수의 이름이 포함되어 있다면, 이렇게하는 것이 최선의 방법입니다. 그러나 데이터가 완전히 안전하지는 않기 때문에 함수 이름을 전달하는 것이 가장 좋은 아이디어는 아닙니다. 함수 객체를 직접 전달하는 것과 같이 다른 디자인을 찾을 수 있다면 더 좋을 것입니다. –

+0

func = globals() [i.header] KeyError : u'func1 ' – Rajeev

+0

이것은'func1'이라는 이름이 당신이 접근하려는 시점에서 정의되지 않았다는 것을 의미합니다. 이 오류를 얻는 방법을 보여주는 완전한 예제를 게시 할 수 있습니까? – shx2

1

을 데코레이터를 사용하는 좋은 방법입니다.

header_handlers = {} 

def header_handler(f): 
    header_handlers[f.__name__] = f 
    return f 

def main(): 
    header_name = "func1" 
    header_handlers[header_name]() 

@header_handler 
def func1(): 
    print "func1" 

@header_handler 
def func2(): 
    print "func2" 

@header_handler 
def func3(): 
    print "func3" 

if __name__ == "__main__": 
    main() 

함수가 헤더 핸들러 또는