python通过字符串类型的函数名调用函数

本文介绍了Python中通过字符串类型函数名来调用函数的几种方式,包括使用eval,结合locals()和globals(),以及利用getattr()函数。此外,还提及了operator模块中的methodcaller函数作为另一种调用策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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))  # <class 'function'>
    
    
  • 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)
    
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值