处理业务相关的数据时,有时候会遇到需要多次使用同一张表格的情况;这张表不大倒还好,一旦它是一张很大的表,重复加载它会导致运行时间变长,若能把它缓存好,就能实现 l o a d o n c e u s e e v e r y w h e r e load \space once \space use \space everywhere load once use everywhere,当然前提是你的内存够用
Last updated: \space 2024/05/26
> Python 3.8 版本
自 P y t h o n 3.8 Python \space 3.8 Python 3.8 开始, f u n c t o o l s functools functools 里新增了
cached_property
函数,只要把它作为我们想要缓存的方法的装饰器即可
创建一个 D a t a Data Data 类
from functools import cached_property
class Data:
@cached_property
def big_table(self):
print('Loading big table...')
return 10
@property
def big_table_normal_property(self):
print('Loading big table in normal_property method...')
return 20
if __name__ == '__main__':
# 初始化
data = Data()
调用被cached_property
装饰的方法
# 连续执行 big_table 五次
[data.big_table for _ in range(5)]
"Loading big table"只打印了一次,说明方法实际只执行了一次,然后它返回的内容就被缓存好了
对比property
方法的输出
# 连续执行 big_table_normal_property 五次
[data.big_table_normal_property for _ in range(5)]
不难看出在每次调用
p
r
o
p
e
r
t
y
property
property 方法时,方法内的代码都重新运行了一次
< Python 3.8 版本
那么问题来了, P y t h o n 3.8 Python\space3.8 Python 3.8之前的版本可以实现嘛
。。。
还真行
创建一个 T e s t Test Test 类
class Test:
@staticmethod
def func_1():
print('Testing...')
return 'func_1'
@staticmethod
def func_2():
return 'func_2'
def __init__(self):
[self.__setattr__(k, v.__get__(object)()) for k, v in Test.__dict__.items() if (not k.startswith('_') & (k == 'func_1'))]
if __name__ == '__main__':
test = Test()
结合类方法__setattr__和staticmethod
使用staticmethod
装饰
f
u
n
c
_
1
func\_1
func_1 ,然后在
_
_
i
n
i
t
_
_
\_\_init\_\_
__init__
方法内
- 通过 _ _ d i c t _ _ \_\_dict\_\_ __dict__ 遍历所有 T e s t Test Test 的方法,剔除所有下划线开头的方法,并且只缓存 f u n c _ 1 func\_1 func_1, i t e m s ( ) items() items() 返回的是键值对 → \rightarrow → { T e s t Test Test 类里的方法名(字符串) : T e s t Test Test 类里的方法对象(object)}
- v . _ _ g e t _ _ ( o b j e c t ) ( ) v.\_\_get\_\_(object)() v.__get__(object)() → \rightarrow → 执行 f u n c _ 1 func\_1 func_1 方法
- s e l f . _ _ s e t a t t r _ _ ( k , v . _ _ g e t _ _ ( o b j e c t ) ( ) ) self.\_\_setattr\_\_(k, v.\_\_get\_\_(object)()) self.__setattr__(k,v.__get__(object)()) → \rightarrow → 重设属性,原来 T e s t . f u n c _ 1 Test.func\_1 Test.func_1返回的是函数对象,现在返回的是 T e s t . f u n c _ 1 Test.func\_1 Test.func_1 执行后的值。(具体自行对比一下 T e s t . f u n c _ 1 Test.func\_1 Test.func_1 和 T e s t . f u n c _ 2 Test.func\_2 Test.func_2就懂了)
通过上述方式就能在类的初始化阶段缓存好你想缓存的属性,从而实现数据复用