python3.8 @cached_property 缓存装饰器

本文介绍了Python3.8引入的新特性`@cached_property`装饰器,它能够将函数转换为对象的缓存属性。首次调用时计算值并存储,后续调用直接从缓存中获取,提高效率。示例中对比了`myfunc`属性与`func1`方法的区别。
from functools import cached_property

class Foo():
    @cached_property
    def myfunc(self):
        print('using myfunc')
        return 20

    def func1(self):
        return 1
if __name__ == '__main__':
    F = Foo()
    print(F.myfunc)
    print('*'*30)
    print(F.myfunc)
    print(F.func1())

最终输出的结果为:

using myfunc
20
******************************
20
1

使用cached_property修饰过的函数,变成了对象的属性,当第一次引用该属性时,会调用该函数,以后再调用该属性时,会直接从字典中取了。

这里 myfunc 是一个属性,而func1是一个方法。

源代码

class cached_property(object):
    """
    Decorator that converts a method with a single self argument into a
    property cached on the instance.
    Optional ``name`` argument allows you to make cached properties of other
    methods. (e.g.  url = cached_property(get_absolute_url, name='url') )
    """
    def __init__(self, func, name=None):
        self.func = func
        self.__doc__ = getattr(func, '__doc__')
        self.name = name or func.__name__
 
    def __get__(self, instance, cls=None):
        if instance is None:
            return self
        res = instance.__dict__[self.name] = self.func(instance)
        return res
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值