본문 바로가기
파이썬

파이썬 How to dynamically call methods within a class using method-name assignment to a variable

by º기록 2021. 1. 16.
반응형
class MyClass:
    def __init__(self, i):
        self.i = i

    def get(self):
        func_name = 'function' + self.i
        self.func_name() # <-- this does NOT work.

    def function1(self):
        pass # do something

    def function2(self):
        pass # do something

다음 오류가 발생합니다. TypeError : 'str'object is not callable

어떻게하면 되나요?

참고 : self.func_name 도 작동하지 않습니다.

 

해결 방법

 

def get(self):
      def func_not_found(): # just in case we dont have the function
         print 'No Function '+self.i+' Found!'
      func_name = 'function' + self.i
      func = getattr(self,func_name,func_not_found) 
      func() # <-- this should work!

 

참조 페이지 https://stackoverflow.com/questions/16642145

 

 

반응형

댓글