小笔记:Python 使用字符串调用函数

小笔记:Python中如何使用字符串调用函数/方法?

jcLee95https://blog.csdn.net/qq_28550263?spm=1001.2101.3001.5343

本文地址https://blog.csdn.net/qq_28550263/article/details/111874476
邮箱 :[email protected]

1. 借助 python字典

2. 借助内置的 getattr() 函数

3. 借助内置 locals() 函数来解析出函数名


【简介】 使用字符串调用函数是一个常用的编程技巧,在大型项目中可以用于实现钩子管理系统。本文指在 介绍 两个 python 内置函数,即 getattr 函数 和 locals 函数。

1. 借助 python字典

最简单的办法是通过一个将字符串映射到函数的字典,例如:

def func1():
    print("func1 was called.")

def func2():
    print("func2 was called.")

d = {
    
    'f1': func1, 'f2': func2} 

d['f1']() 

Out[]:

func1 was called.

2. 借助内置的 getattr() 函数

getattr() 函数用于返回一个对象属性值。其语法格式如下:

getattr(object, name[, default])

其中:

参数 描述
object 对象。
name 字符串,对象属性。
default 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError

例如:

import mymodule
getattr(mymodule, 'myFunc')()

Python 内置的 getattr() 函数可用于任何对象,例如类、类实例、模块等等。

扫描二维码关注公众号,回复: 14648697 查看本文章

通过 getattr() 函数实现按字符串调用函数例如:

class MyClass(object):
    def method1(self):
        print("Method 1 was called.")
    def method2(self):
        print("Method 2 was called.")

my_instance = MyClass()

getattr(my_instance, 'method' + "2")()

Out[]:

Method 2 was called.

注:
这个例子中 getattr(my_instance, 'method' + "2") 是一个函数,因此 getattr(my_instance, 'method' + "2")() 效果上相当于:

func = getattr(my_instance, 'method' + "2")
func()

3. 借助内置 locals() 函数来解析出函数名

Python 中内置的 locals() 函数用于以 字典类型 返回当前位置的 全部 局部变量。

locals() 函数 对于 函数、方法、lambda 表达式、类, 以及所有实现了 __call__ 方法的类实例,它都返回 True。

通过 locals() 函数实现按字符串调用函数如:

def myFunc():
    print("hello")

func_name = "myFunc"

f = locals()[func_name]
f()

Out[]:

hello

猜你喜欢

转载自blog.csdn.net/qq_28550263/article/details/111874476