什么是有条件地返回函数的最pythonic方法 [英] What is the most pythonic way to conditionally return a function

查看:120
本文介绍了什么是有条件地返回函数的最pythonic方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有2个功能。我希望func2返回func1,除非func1返回None,在这种情况下,func2会返回其他内容。有两种方法可以做到这一点,但他们都觉得有些不妥。



我可以这样说:

<$如果(条件):
返回foo

def func2(n):
if($) func1(n)不是None:
return func1(n)
else:
return something_else

但是这种感觉不对,因为我必须调用func1(n)两次(func1(n)是一个更大的计算)。为了解决这个问题,我可以说:

pre $ def func1(n):
if(condition):
返回foo

def func2(n):
foo = func1(n)
如果foo不是无:
返回foo
else:
return something_else

但这种感觉不对,因为我认为我不应该分配一个新的变量,永远不会再次使用,只是为了检查func1是否返回None。



有没有更简单的方法来做到这一点,我不必调用func1两次,我不必创建一个新的变量?如果这个唯一的方法,那么您推荐哪两个?我现在使用第二种方法(我将foo设置为func1返回的内容,而不是返回foo,除非foo == None)。

另外,请记住,在我的真正的代码,我调用了几个不同的函数,并且我想返回第一个不是None的代码,这只是一个简单的代码版本,它可以解决问题。

解决方案

命名为func1的结果的名称相对便宜,所以我会这样做,但要写这样的函数:

  def func2(n):
ret = func1(n)
如果ret不是其他东西,则返回ret something_else


Say I have 2 functions. I want func2 to return func1 UNLESS func1 returns None, in which case func2 returns something else. There are two ways that I could do this, but they both feel slightly wrong.

I could say:

def func1(n):
    if (condition):
        return foo

def func2(n):
    if func1(n) is not None:
        return func1(n)
    else:
        return something_else

But this feels wrong because I have to call func1(n) twice (and func1(n) is a larger computation). To get around that, I could say:

def func1(n):
    if (condition):
        return foo

def func2(n):
    foo = func1(n)
    if foo is not None:
        return foo
    else:
        return something_else

but this feels wrong because I don't think I should have to assign a new variable that will never get used again, just to check if func1 returned None.

Is there an easier way to do this where I don't have to call func1 twice and I don't have to create a new variable? If this is the only way, which of the two would you recommend? I currently have it using the second way (Where I set foo to what func1 returned, than return foo unless foo == None)

Also, keep in mind that in my real code, I call several different functions, and I want to return the first one that is not None, this is just a simpler version of code that gets the question across.

解决方案

Giving a name to the result of calling func1 is relatively cheap, so I'd do that, but write the function like this:

def func2(n):
    ret = func1(n)
    return ret if ret is not None else something_else

这篇关于什么是有条件地返回函数的最pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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