如何将“if"语句传递给函数? [英] How to pass an 'if' statement to a function?

查看:50
本文介绍了如何将“if"语句传递给函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将可选的if"语句传递给要执行的 Python 函数.例如,该函数可能会将一些文件从一个文件夹复制到另一个文件夹,但该函数可以采用可选条件.

I want to pass an optional 'if' statement to a Python function to be executed. For example, the function might copy some files from one folder to another, but the function could take an optional condition.

因此,例如,对该方法的一次调用可以说将文件从源复制到目标 if source.endswith(".exe")

So, for example, one call to the method could say "copy the files from source to dest if source.endswith(".exe")

下一个调用可能只是无条件地将文件从源复制到目标.

The next call could be simply to copy the files from source to destination without condition.

下一个调用可能是将文件从源复制到目标 如果今天是星期一

The next call could be to copy files from source to destination if today is monday

如何将这些条件传递给 Python 中的函数?

How do you pass these conditionals to a function in Python?

推荐答案

函数就是对象.它只是一个返回布尔结果的函数.

Functions are objects. It's just a function that returns a boolean result.

def do_something( condition, argument ):
   if condition(argument):
       # whatever

def the_exe_rule( argument ):
    return argument.endswith('.exe')

do_something( the_exe_rule, some_file )

Lambda 是创建此类函数的另一种方式

Lambda is another way to create such a function

do_something( lambda x: x.endswith('.exe'), some_file )

这篇关于如何将“if"语句传递给函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆