核子可乐译 51CTO
【51CTO快译】在今天的文章中,我们将一同从简单示例出发,了解如何使用缓存机制。在此之后,我们将进一步利用Python标准库的functools模块创建适合自己需要的缓存。闲言少叙,马上开始。
缓存是一种将定量数据加以保存以备迎合后续请求的处理方式,旨在加快数据的检索速度。在今天的文章中,我们将一同从简单示例出发,了解如何使用缓存机制。在此之后,我们将进一步利用Python标准库的functools模块创建适合自己需要的缓存。作为起步工作,我们首先创建一个类,用于构建我们的缓存字典,而后根据需要进行扩展。以下为具体代码:
1
[color=rgb(49, 124, 197) !important]2
3
[color=rgb(49, 124, 197) !important]4
5
[color=rgb(49, 124, 197) !important]6
7
[color=rgb(49, 124, 197) !important]8
[color=rgb(255, 128, 0) !important]########################################################################
[color=rgb(128, 0, 128) !important]class [color=rgb(0, 45, 122) !important]MyCache[color=rgb(0, 111, 224) !important]:
[color=rgb(0, 128, 0) !important]""""""
[color=rgb(255, 128, 0) !important]#----------------------------------------------------------------------
[color=rgb(128, 0, 128) !important]def [color=rgb(0, 78, 208) !important]__init__[color=rgb(51, 51, 51) !important]([color=rgb(128, 0, 128) !important]self[color=rgb(51, 51, 51) !important])[color=rgb(0, 111, 224) !important]:
[color=rgb(0, 128, 0) !important]"""Constructor"""
[color=rgb(128, 0, 128) !important]self[color=rgb(51, 51, 51) !important].cache [color=rgb(0, 111, 224) !important]= [color=rgb(51, 51, 51) !important]{[color=rgb(51, 51, 51) !important]}
[color=rgb(128, 0, 128) !important]self[color=rgb(51, 51, 51) !important].[color=rgb(0, 45, 122) !important]max_cache[color=rgb(51, 51, 51) !important]_size [color=rgb(0, 111, 224) !important]= [color=rgb(206, 0, 0) !important]10