首页 > 解决方案 > Python:动态定义类的函数

问题描述

我想在一个依次运行多个函数的类中创建一个函数。但是执行什么函数应该取决于条件,例如可以将结果写入磁盘或数据库或两者的函数。但是通过数百万次计算,我不想要一个 if 语句每次都询问数据库或磁盘写入的条件在该单个函数中是 True 还是 False。我想知道什么是最好的解决方案。我可以编写某种选择函数(),如果条件为真,则用函数填充列表,并在编写函数中执行该列表中的所有函数。或者创建一个仅在满足条件时才具有这些功能的写作类,并将它们作为写作功能继承到主类。做这种事情的常见方法是什么?

标签: pythonclassinheritancedynamic

解决方案


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")

推荐阅读