Python通过函数名动态调用函数的两种核心方法:eval与getattr

林见深
林见深
发布时间:2026-10-14| 5人浏览过
原创

本文详解Python中通过字符串函数名动态调用函数的两种主流方案:eval与getattr。eval适用于简单表达式或类内直接调用,需注意安全风险;getattr则通过反射机制获取函数对象,支持跨类、跨模块调用,更为灵活安全。文章提供类内、同级函数及跨文件调用的完整代码示例,帮助开发者掌握动态执行逻辑的最佳实践。

Python动态调用函数概述

一、说明

此前曾发布过“Python执行系统命令教程”,介绍了如何执行外部系统命令。

除执行系统命令外,开发中常需动态执行Python代码。熟悉Python的开发者知道,可使用内置函数eval实现,例如eval("print(__file__)"),这种方式相对简单。

然而,若需动态执行特定函数,相关参考资料较少。本文将重点探讨如何实现通过函数名动态调用函数的需求。

使用eval动态执行函数

二、通过eval实现

2.1 通过eval调用同一个类内的函数


class TestA:
 def __init__(self):
  self.config_dict = {
   "be_called_function_name": "self.be_called_function()",
  }
  pass

 def active_call_function(self):
  print("here is active_call_function.")
  be_called_function_name = self.config_dict["be_called_function_name"]
  # 就直接调用。如果有其他参数,一样地传就好了
  # 另外也可以是"be_called_function_name"是"be_called_function",然后eval(be_called_function_name)()
  eval(be_called_function_name)
  pass

 def be_called_function(self):
  print("here is be_called_function.")

if __name__ == "__main__":
 obj = TestA()
 obj.active_call_function()

2.2 通过eval调用同一个文件内的一级函数


class TestA:
 def __init__(self):
  self.config_dict = {
   "be_called_function_name": "be_called_function()",
  }
  pass

 def active_call_function(self):
  print("here is active_call_function.")
  be_called_function_name = self.config_dict["be_called_function_name"]
  # 就直接调用。如果有其他参数,一样地传就好了
  # 另外也可以是"be_called_function_name"是"be_called_function",然后eval(be_called_function_name)()
  eval(be_called_function_name)
  pass

def be_called_function():
 print("here is be_called_function.")

if __name__ == "__main__":
 obj = TestA()
 obj.active_call_function()

使用getattr反射调用函数

三、通过getattr实现

3.1 通过函数名调用同一个类内的函数


class TestA:
 def __init__(self):
  self.config_dict = {
   "be_called_function_name": "be_called_function",
  }
  pass

 def active_call_function(self):
  print("here is active_call_function.")
  # getaattr(module_name, function_name),module_name传self即可
  be_called_function = getattr(self, self.config_dict["be_called_function_name"])
  # 就直接调用。如果有其他参数,一样地传就好了
  be_called_function()
  pass

 def be_called_function(self):
  print("here is be_called_function.")


if __name__ == "__main__":
 obj = TestA()
 obj.active_call_function()

3.2 通过函数名调用其他类的函数


class TestA:
 def __init__(self):
  self.config_dict = {
   "be_called_function_name": "be_called_function",
  }
  pass

 def active_call_function(self):
  print("here is active_call_function.")
  # getaattr(module_name, function_name),module_name传被调用的函数所在的类的类实例
  testb_obj = TestB()
  be_called_function = getattr(testb_obj, self.config_dict["be_called_function_name"])
  # 就直接调用。如果有其他参数,一样地传就好了
  be_called_function()
  pass


class TestB:
 def be_called_function(self):
  print("here is be_called_function.")


if __name__ == "__main__":
 obj = TestA()
 obj.active_call_function()

3.3 通过函数名调用同文件的一级函数


import sys


class TestA:
 def __init__(self):
  self.config_dict = {
   "be_called_function_name": "be_called_function",
  }
  pass

 def active_call_function(self):
  print("here is active_call_function.")
  # getaattr(module_name, function_name),module_name传当前模块名
  module_name = sys.modules['__main__']
  be_called_function = getattr(module_name, self.config_dict["be_called_function_name"])
  # 就直接调用。如果有其他参数,一样地传就好了
  be_called_function()
  pass


def be_called_function():
 print("here is be_called_function.")


if __name__ == "__main__":
 obj = TestA()
 obj.active_call_function()

3.4 通过函数名调用在其他文件的一级函数


class TestA:
 def __init__(self):
  self.config_dict = {
   "be_called_function_name": "be_called_function",
  }
  pass

 def active_call_function(self):
  print("here is active_call_function.")
  # getaattr(module_name, function_name),module_name传函数所在模块名
  # __import__()传函数所在文件
  module_name = __import__("test_call_function_by_string1")
  be_called_function = getattr(module_name, self.config_dict["be_called_function_name"])
  # 就直接调用。如果有其他参数,一样地传就好了
  be_called_function()
  pass


if __name__ == "__main__":
 obj = TestA()
 obj.active_call_function()

以上即为Python通过函数名调用函数的几种常见场景与实现方式,更多Python动态调用相关技术细节,欢迎查阅本站其他文章。

相关标签:

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。