python通过函数名调用函数的几种场景


Posted in Python onSeptember 23, 2020

一、说明

之前写了一篇“Python执行系统命令教程”讲了如何执行系统命令。

除了执行系统命令外,我们有时还需要动态地执行一些python代码,有经验的朋友就会知道可以使用内置函数eval实现这一需求,如eval("print(__file__)"),这还是比较简单的。

但如果要动态执行一个函数,讲的资料就会少一点,这次就要看这个需求该如何实现。

二、通过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实现

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 相关文章推荐
Python实现模拟登录及表单提交的方法
Jul 25 Python
python妙用之编码的转换详解
Apr 21 Python
Python多进程池 multiprocessing Pool用法示例
Sep 07 Python
解决PyCharm的Python.exe已经停止工作的问题
Nov 29 Python
python实现汽车管理系统
Nov 30 Python
python将txt等文件中的数据读为numpy数组的方法
Dec 22 Python
新手入门Python编程的8个实用建议
Jul 12 Python
python自动化UI工具发送QQ消息的实例
Aug 27 Python
python mqtt 客户端的实现代码实例
Sep 25 Python
PyTorch: Softmax多分类实战操作
Jul 07 Python
Python如何将模块打包并发布
Aug 30 Python
python 如何在list中找Topk的数值和索引
May 20 Python
Python如何执行系统命令
Sep 23 #Python
Python SMTP发送电子邮件的示例
Sep 23 #Python
python两个list[]相加的实现方法
Sep 23 #Python
python matplotlib库的基本使用
Sep 23 #Python
15个应该掌握的Jupyter Notebook使用技巧(小结)
Sep 23 #Python
Python读取多列数据以及用matplotlib制作图表方法实例
Sep 23 #Python
PyCharm 2020.2下配置Anaconda环境的方法步骤
Sep 23 #Python
You might like
php,不用COM,生成excel文件
2006/10/09 PHP
最简单的PHP程序--记数器
2006/10/09 PHP
php 分页原理详解
2009/08/21 PHP
关于php循环跳出的问题
2013/07/01 PHP
php微信开发之关键词回复功能
2018/06/13 PHP
ASP.NET jQuery 实例8 (动态添加内容到DropDownList)
2012/02/03 Javascript
js实现单一html页面两套css切换代码
2013/04/11 Javascript
ajax提交表单实现网页无刷新注册示例
2014/05/08 Javascript
jQuery DOM插入节点操作指南
2015/03/03 Javascript
JS在onclientclick里如何控制onclick的执行
2016/05/30 Javascript
Bootstrap的modal拖动效果
2016/12/25 Javascript
Vue.js仿Metronic高级表格(一)静态设计
2017/04/17 Javascript
ES6入门教程之Class和Module详解
2017/05/17 Javascript
基于react框架使用的一些细节要点的思考
2017/05/31 Javascript
JavaScript转换数据库DateTime字段类型方法
2017/06/27 Javascript
Bootstrap提示框效果的实例代码
2017/07/12 Javascript
WebSocket的通信过程与实现方法详解
2018/04/29 Javascript
[54:57]DOTA2-DPC中国联赛定级赛 Aster vs DLG BO3第二场 1月8日
2021/03/11 DOTA
Python的词法分析与语法分析
2013/05/18 Python
python实现杨辉三角思路
2017/07/14 Python
Python基于Pymssql模块实现连接SQL Server数据库的方法详解
2017/07/20 Python
python实现控制电脑鼠标和键盘,登录QQ的方法示例
2019/07/06 Python
利用matplotlib实现根据实时数据动态更新图形
2019/12/13 Python
python itsdangerous模块的具体使用方法
2020/02/17 Python
Python MOCK SERVER moco模拟接口测试过程解析
2020/04/13 Python
美国购买体育赛事门票网站:TicketCity
2019/03/06 全球购物
德国亚洲食品网上商店:asiafoodland.de
2019/12/28 全球购物
定义一结构体变量,用其表示点坐标,并输入两点坐标,求两点之间的距离
2015/08/17 面试题
HSRP的含义以及如何工作
2014/09/10 面试题
什么是虚拟内存?虚拟内存有什么优势?
2012/02/19 面试题
2014全国两会大学生学习心得体会
2014/03/10 职场文书
小学毕业典礼演讲稿
2014/09/09 职场文书
SpringBoot整合Mybatis Generator自动生成代码
2021/08/23 Java/Android
Golang中channel的原理解读(推荐)
2021/10/16 Golang
CentOS 7安装mysql5.7使用XtraBackUp备份工具命令详解
2022/04/12 MySQL
pandas时间序列之pd.to_datetime()的实现
2022/06/16 Python