擅长:python、mysql、java
<p><strong>为现代Python更新了答案</strong></p>
<p>对于仍在搜索如何执行此操作的任何人,标准库<code>functools</code>包含一个装饰函数<a href="https://docs.python.org/3/library/functools.html#functools.lru_cache" rel="nofollow noreferrer">^{<cd2>}</a>来执行此操作。</p>
<p>例如(来自文档):</p>
<pre><code>@lru_cache(maxsize=32)
def get_pep(num):
'Retrieve text of a Python Enhancement Proposal'
resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
try:
with urllib.request.urlopen(resource) as s:
return s.read()
except urllib.error.HTTPError:
return 'Not Found'
</code></pre>
<p>这将存储对<code>32</code>的最后一次<code>get_pep</code>调用,当使用相同参数调用时,将返回缓存值。</p>