2016-08-11 52 views
0

我有一個簡單的Python 2.7版的功能,稱之爲det2x2在下面的代碼所示:Python函數的返回值應該是方程還是局部變量?

def det2x2(a, b, c, d): 
    return a*d - b*c 

它是更Python或建議去做,而不是這樣?

def det2x2(a, b, c, d): 
    result = a*d - b*c 
    return result 

我意識到,對於這個簡單的函數,它可能並不重要,但對於更精細的計算它可能。

回答

0

在第二個示例中,您正在創建一個引用'result',然後在下一行返回該引用的值。

所以只需返回值。

def det2x2(a, b, c, d): 
    return a*d - b*c 

2的理由做這種方式:

A.更少的代碼讀取(主要原因)

B.略顯不足內存

import sys 
def det2x2(a, b, c, d): 
    result = a*d - b*c 
    print sys.getsizeof(result) 
    return result 
>>> det2x2(1, 2, 3, 4) 
24 # you just used 24 bytes of memory for 'result' reference 
-2 # answer 
相關問題