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)
    
    

你可能感兴趣的:(新知识,python,总结)