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

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

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


【简介】 使用字符串调用函数是一个常用的编程技巧,在大型项目中可以用于实现钩子管理系统。本文指在 介绍 两个 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() 函数可用于任何对象,例如类、类实例、模块等等。

通过 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
目录
相关文章
|
17天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
203 100
|
17天前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
244 99
|
20天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
20天前
|
开发者 Python
Python f-strings:更优雅的字符串格式化技巧
Python f-strings:更优雅的字符串格式化技巧
|
20天前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
1月前
|
Python
使用Python f-strings实现更优雅的字符串格式化
使用Python f-strings实现更优雅的字符串格式化
|
2月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
218 92
|
2月前
|
数据采集 存储 数据库
Python字符串全解析:从基础操作到高级技巧
Python字符串处理详解,涵盖基础操作、格式化、编码、正则表达式及性能优化等内容,结合实际案例帮助开发者系统掌握字符串核心技能,提升文本处理与编程效率。
177 0
|
2月前
|
存储 小程序 索引
Python变量与基础数据类型:整型、浮点型和字符串操作全解析
在Python编程中,变量和数据类型是构建程序的基础。本文介绍了三种基本数据类型:整型(int)、浮点型(float)和字符串(str),以及它们在变量中的使用方式和常见操作。通过理解变量的动态特性、数据类型的转换与运算规则,初学者可以更高效地编写清晰、简洁的Python代码,为后续学习打下坚实基础。
387 0

热门文章

最新文章

推荐镜像

更多