Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何检查python函数输出并将其分配给变量,而无需执行函数两次?_Python_Design Patterns - Fatal编程技术网

如何检查python函数输出并将其分配给变量,而无需执行函数两次?

如何检查python函数输出并将其分配给变量,而无需执行函数两次?,python,design-patterns,Python,Design Patterns,假设我想做以下几件事 def calculate_something_extremally_resource_consuming(): # execute some api calls and make insane calculations if calculations_sucessfull: return result 同时,在项目的其他地方: if calculate_something_extremally_resource_consuming():

假设我想做以下几件事

def calculate_something_extremally_resource_consuming():
    # execute some api calls and make insane calculations
    if calculations_sucessfull:
        return result
同时,在项目的其他地方:

if calculate_something_extremally_resource_consuming():
    a = calculate_something_extremally_resource_consuming()
    etc...
看起来重载函数将被调用两次,这非常糟糕。我可以想象的另一个选择是:

a = calculate_something_extremally_resource_consuming()
if a:
    etc...

也许有一种更优雅的方法?

在某些语言中,您可以将变量指定为条件块的一部分,但在Python中,这是不可能的(请参见)

有时可以帮助您:

Decorator将函数包装为一个memonizing可调用函数,可将最近的调用保存为maxsize。当使用相同的参数周期性地调用昂贵的或I/O绑定的函数时,它可以节省时间

这在Python3.2中是新的。如果您使用的是旧Python,那么很容易编写自己的装饰程序


如果您在类上使用方法/属性,则此选项非常有用

第三个选项是我使用的。有什么不喜欢的?
>>> from functools import lru_cache
>>> from time import sleep
>>> @lru_cache()
... def expensive_potato():
...     print('reticulating splines...')
...     sleep(2)
...     return 'potato'
... 
>>> expensive_potato()
reticulating splines...
'potato'
>>> expensive_potato()
'potato'