Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

Python: Change recurrent if statement for a function or an alternative

I am using a recurrent if statement for multiple variables, all of them are following the same condition, BUT! very important, all of them are independent, also the functions asociated to the variables are. Sometimes you execute only one function, sometimes another, sometimes all of them.

My actual code looks something like this:

if len(variable) != 0 or variable_1 is not None:
    exec_func_1(variable_1)

if len(variable_2) != 0 or variable_2 is not None:
    exec_func_2(variable_2)

if len(variable_3) != 0 or variable_3 is not None:
    exec_func_3(variable_3)

I am looking to replace the if for something like a function or a simpler line of code, since it could be repeating the same thing numerous times in my code. an example would be like:

def use_condition(variable):
    # obiously doesn't work hahah
    if len(variable) != 0 or variable is not None:
        pass

Because if I change 1 parameter in my if statement it could be nice to change it in all the "if" statements at the same time


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can pass functions as parameters of another function like this:

def use_condition(var, func):
    if (len(var) != 0 or var is not None:
        func(var)

Which you can then just call with the variable and the execution function you want:

use_condition(variable_1, exec_func_3)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...