我有以下功能:
def f(x):
return x
def f2(x):
y = f(x)
return y + x + 1
def f3(x):
y = f(x)
return y + x + 2
def DoAll(x):
i2 = f2(x)
i3 = f3(x)
return i2, i3
print(DolAll(2))
即使这段代码运行,由于我f(x)
多次调用,它似乎效率很低。如何在不定义f2(x, y)
and的情况下解决这个问题f3(x, y)
?我想使用类似的东西
def f(x):
return x
def f2(x):
nonlocal y
return y + x + 1
def f3(x):
nonlocal y
return y + x + 2
def DoAll(x):
y = f(x)
f2 = f2(x)
f3 = f3(x)
return f2, f3
print(DolAll(2))
当然,这里显示的代码不起作用。
您可以使用缓存来避免重做计算。Python 开箱即用地提供了这样的功能functools.lru_cache
:
from functools import lru_cache
@lru_cache()
def f(x):
...
这比仅仅让值全局可用更通用,因为它允许多个计算同时存储值。
如果您的函数是确定性的并且没有副作用,您也可以通过缓存所有中间结果来完全缩短嵌套调用的计算:
@lru_cache()
def f(x):
print(f'Called f({x})')
return x
@lru_cache()
def f2(x):
print(f'Called f2({x})')
y = f(x)
return y + x + 1
@lru_cache()
def f3(x):
print(f'Called f3({x})')
y = f(x)
return y + x + 2
@lru_cache()
def DoAll(x):
print(f'Called DoAll({x})')
i2 = f2(x)
i3 = f3(x)
return i2, i3
>>> DoAll(1)
Called DoAll(1)
Called f2(1)
Called f(1)
Called f3(1)
(3, 4)
>>> DoAll(2)
Called DoAll(2)
Called f2(2)
Called f(2)
Called f3(2)
(5, 6)
>>> DoAll(1)
(3, 4)
请注意,对于每个新输入,昂贵的计算只会执行一次。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句