2016-08-11 57 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 
相关问题