简体   繁体   中英

Define function and it's parameter based on configuration in python

I have to written a python script with class and its function. The function parameters shall be varied based on configuration. In 'C' language it can achieved using #ifdef or #if Macro

#ifdef MULTIPLE_APPLICATION
uint8 check_actions(int machine, int application_instance, int error_limit)
{
          .....
}
#else /*single applciation*/
uint8 check_actions(int machine, int error_limit)
{
        .....
}

In same way how can i achieve in python. Because i don't find anything that replace #ifdef in python. i want something like

#ifdef MULTIPLE_APPLICATION
def check_actions(self, machine, application_instance, error_limit)
#else
def check_actions(self, machine, error_limit)
    .......
    .......

python is an pure OOP language. There is no #if macros. the consipt is totaly diffrent here. you can solve it in many ways. one of the simple ways is to define outer function and 2 nested inner functions and call one of the inner functions coresponding to var that you pass to the outer functions: see below:

def check_action(application_stat, *args, **kwargs):
    def check_single_app_action(*args, **kwargs):
        #do some thing
        return
    def check_multi_app_action(*args, **kwargs):
        #do some work
        return
    if application_stat=='single':
        check_single_app_action(args, kwargs) 
    else:
        check_multi_app_action(args, kwargs)
    return

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