繁体   English   中英

强制Python在返回0或无时返回0

[英]Force Python to return 0 when returning 0 or None

在递归调用的结尾,我的代码中包含以下部分:

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应该作为整数返回。

Python表现为None,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'

如果是特定情况,则可以使用装饰器。 下面的例子:

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

单击此处以进一步了解装饰器。

内联,否则:

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

通过使用+算术运算符, ab被求值,不会像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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM