简体   繁体   中英

creating function object with conditional statement before calling

I have defined two functions(fun1 and fun2), which return some values and I call one of these functions in fun3. I can do if condition inside for loop but is there a way that the function can be chosen before. As shown here. Or is there any other approach?

def fun1(a1,b1)
def fun2(a1,b1)

def fun3(a1,b1,some_para):

    if some_para:
        sel_func = fun1()
    else:
        sel_func = fun2()

    for Loop:
        sel_func(a1,b1)

Functions are objects. Just assign the function instead of calling it. Using your example:

def fun3(a1, b1, some_para):

    sel_func = fun1 if some_para else fun2

    for Loop:
        sel_func(a1, b1)
def fun1(a1,b1)
def fun2(a1,b1)


def fun3(a1,b1,some_para = None):
    sel_func = fun1  if some_para else fun2
    for Loop:
        sel_func(a1,b1)

use some_para =None in function declaration, when you call this function you always need to pass the argument to it and only fun1 will run every time if you don't pass any value an attribute error will occur. if none uses and no value passed fun2 will execute else fun1 will.

You can pass the function as a parameter outside so it is easier to read:

def fun3(a1, b1, sel_func):
    for Loop:
        sel_func(a1, b1)

# call fun3 with whatever funtion you need in each momment
fun3(a, b, fun1) 
fun3(a, b, fun2)

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