python - Python:动态定义类的函数
问题描述
我想在一个依次运行多个函数的类中创建一个函数。但是执行什么函数应该取决于条件,例如可以将结果写入磁盘或数据库或两者的函数。但是通过数百万次计算,我不想要一个 if 语句每次都询问数据库或磁盘写入的条件在该单个函数中是 True 还是 False。我想知道什么是最好的解决方案。我可以编写某种选择函数(),如果条件为真,则用函数填充列表,并在编写函数中执行该列表中的所有函数。或者创建一个仅在满足条件时才具有这些功能的写作类,并将它们作为写作功能继承到主类。做这种事情的常见方法是什么?
解决方案
import sys
def log(name):
print("running:" + name)
def proc1():
log ( sys._getframe().f_code.co_name)
def proc2():
log ( sys._getframe().f_code.co_name)
def proc3():
log ( sys._getframe().f_code.co_name)
def procA():
log ( sys._getframe().f_code.co_name)
def procB():
log ( sys._getframe().f_code.co_name)
def procC():
log ( sys._getframe().f_code.co_name)
def setMyFunctions(conditions):
# set your funtions here
option = {
1: [proc1, proc2, proc3],
2: [procA, procB, procC],
};
return option[conditions]
# ready to run as is, just try it
x = True # change the x here to see the inpact
if (x):
status = 1
else:
status = 2
toDoList = setMyFunctions(status)
i = 0; lastTask = len(toDoList)
# log the start
print ( "main started")
while i < lastTask:
# run or deliver your task list here
toDoList[i]()
i += 1
print ( "main finished")
推荐阅读
- html - 如何通过 asp.net 中的 web api 发送静态 html 数据?
- c++ - 为 std::array 指定更大的大小后未处理的异常
- angular - 由于未在 5000 毫秒内调用异步回调(由 jasmine.DEFAULT_TIMEOUT_INTERVAL 设置),角单元测试随机失败
- bash - Snakemake 将 conda 激活命令更改为“conda activate”
- python - PANDAS - 当它适用于一个系列时,日期显示错误 NaN 而不是日期,但不适用于另一个系列。两者都有完全相同的方法
- azure - Powerapps 的 ALM
- javascript - 地理位置 MongoDB 查询 maxDistance
- variables - 如何在 terraform 中为 s3 后端声明变量?
- java - 如何将 Proto 对象序列化/反序列化到 Android 项目中的本地存储?
- dask - 来自库的 Dask 循环开销