Development Tip

Python : 문자열 이름에서 함수 호출

yourdevel 2020. 11. 9. 21:15
반응형

Python : 문자열 이름에서 함수 호출


이 질문에 이미 답변이 있습니다.

예를 들어 str 개체가 menu = 'install'있습니다.. 이 문자열에서 설치 방법을 실행하고 싶습니다. 예를 들어 내가 전화 menu(some, arguments)하면 install(some, arguments). 그렇게 할 방법이 있습니까?


클래스에 있으면 getattr을 사용할 수 있습니다.

class MyClass(object):
    def install(self):
          print "In install"

method_name = 'install' # set by the command line options
my_cls = MyClass()

method = None
try:
    method = getattr(my_cls, method_name)
except AttributeError:
    raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))

method()

또는 함수 인 경우 :

def install():
       print "In install"

method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
     raise NotImplementedError("Method %s not implemented" % method_name)
method()

사전을 사용할 수도 있습니다.

def install():
    print "In install"

methods = {'install': install}

method_name = 'install' # set by the command line options
if method_name in methods:
    methods[method_name]() # + argument list of course
else:
    raise Exception("Method %s not implemented" % method_name)

왜 eval ()을 사용할 수 없습니까?

def install():
    print "In install"

새로운 방법

def installWithOptions(var1, var2):
    print "In install with options " + var1 + " " + var2

그런 다음 아래와 같이 메서드를 호출합니다.

method_name1 = 'install()'
method_name2 = 'installWithOptions("a","b")'
eval(method_name1)
eval(method_name2)

이것은 출력을 다음과 같이 제공합니다.

In install
In install with options a b

참고 URL : https://stackoverflow.com/questions/7936572/python-call-a-function-from-string-name

반응형