『Python』数据复用 - 缓存属性

处理业务相关的数据时,有时候会遇到需要多次使用同一张表格的情况;这张表不大倒还好,一旦它是一张很大的表,重复加载它会导致运行时间变长,若能把它缓存好,就能实现 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__
方法内

  1. 通过 _ _ 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)}
  2. 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 方法
  3. 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就懂了)

在这里插入图片描述

通过上述方式就能在类的初始化阶段缓存好你想缓存的属性,从而实现数据复用

  • 28
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值