返回0或无

时间:2017-09-20 06:18:50

标签: python python-3.x

在递归调用结束时,我的代码中有一个部分如下:

if (condition):
    # Some code here
else:
    return function_call(some_parameters) or function_call(some_parameters)

它可以评估为

return None or 0

它将返回0(整数,如预期的那样) 或

return 0 or None

它将返回None(预期0)

我的问题是,是否有可能让Python在上面的情况下返回0(作为INTEGER)?

以下是代表方案的一些代码

$ cat test.py
#!/usr/bin/python3
def test_return():
    return 0 or None
def test_return2():
    return None or 0
def test_return3():
    return '0' or None #Equivalent of `return str(0) or None`

print( test_return() )
print( test_return2() )
print( test_return3() )

$ ./test.py
None
0
0

注意:0应该以整数形式返回。

3 个答案:

答案 0 :(得分:3)

Python表现为无,0,{},[],''作为Falsy。其他值将被视为Truthy 所以以下是正常行为

def test_return():
    return 0 or None   # 0 is Falsy so None will be returned
def test_return2():
    return None or 0   # None is Falsy so 0 will be returned
def test_return3():
    return '0' or None # '0' is Truthy so will return '0'

答案 1 :(得分:1)

如果是特定情况,您可以使用装饰器。示例如下:

def test_return(f):
    def wrapper():
        result = f()
        if result == None or result == '0':
            return 0
        else:
            return result
    return wrapper

@test_return
def f1():
    return 0 or None

@test_return
def f2():
    return None or 0

@test_return
def f3():
    return '0' or None

输出:

print(f1())
print(f2())
print(f3())

0
0
0

点击此处查看further read on decorators.

答案 2 :(得分:0)

内联if else:

return 0 if (a == 0) + (b == 0) else None

使用+算术运算符评估ab,没有' shortcircuit'与or

一样

其中ab代表你的函数调用

tst = ((0, 0), (0, None), (None, 0), (None, None))


[0 if (a == 0) + (b == 0) else None for a, b in tst]
Out[112]: [0, 0, 0, None]