Pythonic方法避免“if x:return x”语句 - Pythonic way to avoid “if x: return x” statements

10/14 01:51
阅读数 0

问题:

I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy. 我有一个方法,按顺序调用其他4个方法来检查特定的条件,并在每次返回Truthy时立即返回(不检查以下的方法)。

def check_all_conditions():
    x = check_size()
    if x:
        return x

    x = check_color()
    if x:
        return x

    x = check_tone()
    if x:
        return x

    x = check_flavor()
    if x:
        return x
    return None

This seems like a lot of baggage code. 这似乎是很多行李代码。 Instead of each 2-line if statement, I'd rather do something like: 而不是每个2行if语句,我宁愿做类似的事情:

x and return x

But that is invalid Python. 但那是无效的Python。 Am I missing a simple, elegant solution here? 我在这里错过了一个简单优雅的解决方案吗? Incidentally, in this situation, those four check methods may be expensive, so I do not want to call them multiple times. 顺便说一句,在这种情况下,这四种检查方法可能很昂贵,所以我不想多次调用它们。


解决方案:

参考一: https://en.stackoom.com/question/2RXpf
参考二: https://stackoom.com/question/2RXpf
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部