2017-09-20 95 views
0

我有一個遞歸調用結束時我的一段代碼如下:力Python來返回0,或無時返回0

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應爲整數返回。

+2

你爲什麼這樣做呢?只需鍵入0,那麼它將始終返回0. – Alperen

+1

其他可能的返回結果是什麼? – Fejs

+0

...'x = fun(); y = f();'然後'如果x不是None else y就返回x? –

回答

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

您可以使用裝飾,如果它的一個特例。下面的例子:

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.

0

內嵌的if else:

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

使用+算術運算符都ab進行評估,沒有'shor tcircuit」與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]