Skip to main content
 首页 » 编程设计

python之如果函数满足条件而不使用额外变量,则使用函数的返回值

2024年10月01日8hnrainll

假设函数 some_function(x) 返回一个整数,我目前正在执行以下操作:

def another_function(): 
    # stuff... 
    result = some_function(x) 
    if result != 0: 
        return result 
    # else: more stuff (unrelated to result)... 

我要的是找到最好的写法

if some_function(x) != 0: 
    return some_function(x) 

当然没有调用 some_function(x) 两次。

在不使用 result 的情况下,是否有更“聪明”的惯用方式在 Python 3 中编写它?

请您参考如下方法:

另一种选择是定义在函数给出 0 作为结果时引发的异常。如果是这种情况,请捕获错误并执行其他操作。

class ZeroResult(Exception): 
    def __init__(self): 
        raise AttributeError 
 
def some_function(x): 
    #... 
    if result==0: 
        raise ZeroResult 
    else: 
        return result 
 
def another_function(): 
    # stuff 
    try: 
        return some_function(x) 
    except ZeroResult: 
        # more stuff