简体   繁体   中英

Python: Dynamically define functions of a class

I want to create a function in a class that sequently runs a number of functions. But what functions are executed should depend on conditions, for example a function that could write results to the disk or to a database or to both of that. But with millions of calculations I dont want a if statement that asked everytime if the condtion for database or disk writing is True or False in that single function. I wonder what is the best solution for that. I could write some kind of choseFunction(), that fills a list with functions if conditions are True and execute all functions in that list in the writing functions. Or create a Writing Class that only have those functions if they met the condtions and inherit them to the main class as writing function. What is the common way to do such a thing?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM