擅长:python、mysql、java
<p>您可以使用<a href="https://docs.python.org/3/library/functools.html" rel="noreferrer">^{<cd1>}</a>来进行缓存。我接受<code>maxsize</code>参数来控制它的缓存量:</p>
<pre><code>from functools import lru_cache
@lru_cache(maxsize=2)
def test(n):
print("calling function")
return n * 2
print(test(2))
print(test(2))
print(test(3))
print(test(3))
print(test(4))
print(test(4))
print(test(2))
</code></pre>
<p>结果:</p>
<blockquote>
<p>calling function<br/>
4<br/>
4<br/>
calling function<br/>
6<br/>
6<br/>
calling function<br/>
8<br/>
8<br/>
calling function<br/>
4 </p>
</blockquote>