假设我想做以下事情
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...
也许有更优雅的方式?你知道吗
^{} 有时可以帮助您:
这是python3.2中的新特性。如果您使用的是老Python,那么很容易编写自己的decorator。你知道吗
如果您使用的是类的方法/属性,^{} 很有用。你知道吗
在某些语言中,可以将变量指定为条件块的一部分,但在Python中这是不可能的(请参见Can we have assignment in a condition?)
相关问题 更多 >
编程相关推荐