python文字列タイプの関数名で関数を呼び出す


python文字列タイプの関数名で関数を呼び出す
  • eval
    def func():
        print("hello world")
    
    
    if __name__ == '__main__':
        str01 = "func"
        str_2_func = eval(str01)
        str_2_func()  # hello world
        print(type(str_2_func))  # 
    
    
  • locals()およびglobals()
    def func01():
        print("hello world func01")
    
    
    def func02():
        print("hello world func02")
    
    
    if __name__ == '__main__':
        locals()['func01']()  # hello world func01
        globals()['func02']()  # hello world func02
    
    
  • getattr()
    # python     ,getattr(object,name)   object.name
    
    class A(object):
        def to_eat(self):
            print("eat")
    
        def to_sleep(self):
            print("sleep")
    
    
    if __name__ == "__main__":
        a = A()
        #   1:object   
    	#   2:name          
        func01 = getattr(a, "to_eat")
        func01()
        func02 = getattr(a, "to_sleep")
        func02()
    
    
  • operatorのmethodcaller関数
    #    operator  methodcaller  ,             AttributeError  
    
    from operator import methodcaller
    
    
    class A(object):
        def func(self):
            print("func")
    
    
    if __name__ == '__main__':
        a = A()
        # methodcaller(         )(    )
        methodcaller("func")(a)