【问题标题】:python: run the second condition after the first one becomes falsepython:在第一个条件变为假后运行第二个条件
【发布时间】:2021-11-26 08:27:07
【问题描述】:

我有一个脚本,其中给出了 if-else 条件,if 接受用户输入并处理如果某个目录为空并填充该特定目录,如果目录已满则 else 运行。

if not any(fname.endswith('.csv') for fname in os.listdir(certain_dir)): 
    def process_user_input:
     ....code....
        return something
else:
    def do_process_on_the_full_directory:
     ....code....
        return something_else

因此,如果目录为空,则第一个条件变为 True 并发生第一个过程,然后我必须再次运行脚本以在现在已满的目录上运行 else 条件。 我的问题是是否有更好的方法来做到这一点,所以我不必运行脚本两次来获得我想要的,例如,如果有办法添加订单(首先,完成 first 条件,second 目录被填满后运行第二个条件)。

【问题讨论】:

    标签: python process conditional-statements


    【解决方案1】:

    我们可以在这里利用decorators1 来强制执行不变量。

    def fill_if_empty(func):
        def wrapper(*args, **kwargs):
            if YOUR_CONDITION_TO_CHECK_FOR_EMPTY_DIR:
                """
                fill empty directory here.
                """
                process_user_input()
    
            func(*args, **kwargs)
        return wrapper
    
    @fill_if_empty
    def do_process_on_the_full_directory():
        """
        Run some process on directory
        """
        pass
    
    do_process_on_full_directory() 
    

    1. 查看这篇文章了解更多关于装饰器的信息:How to make function decorators and chain them together?

    【讨论】:

    • 非常感谢您的回复。我还有一个问题,因为我以前没有使用过装饰器,我现在想知道我是否需要从 fill_if_empty 函数返回一些东西,我应该在哪里有那个 return 语句?我问这个是因为在我的问题中 process_user_input 函数返回了一些东西
    • @zarakolagar 装饰器不过是一个将函数作为输入并对其进行处理并返回一个函数的函数。以上与fill_if_empty(do_process_on_the_full_directory)() 相同,因此您的装饰器应该返回一个函数。你可以阅读更多关于它的详细信息here
    猜你喜欢
    • 2014-12-30
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 2020-06-26
    • 2013-05-12
    • 1970-01-01
    相关资源
    最近更新 更多