cached_property/缓存属性

# cached_property 缓存属性
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):
        # print(f'f: {id(func)}')
        self.func = func
        self.__doc__ = getattr(func, '__doc__')
        self.name = name or func.__name__

    def __get__(self, instance, type=None):
        # print(f'self func: {id(self.func)}')
        # print(f'instance: {id(instance)}')
        if instance is None:
            return self
        res = instance.__dict__[self.name] = self.func(instance)
        return res


class F00():
    @cached_property
    def test(self):
        # cached_property 将会把每个实例的属性存储到实例的__dict__中, 实例获取属性时, 将会优先从__dict__中获取,则不会再次调用方法内部的过程
        print(f'运行test方法内部过程')
        return 3
    
    @property
    def t(self):
        print('运行t方法内部过程')
        return 44


f = F00()
print(f.test)  # 第一次将会调用test方法内部过程
print(f.test)  # 再次调用将直接从实例中的__dict__中直接获取,不会再次调用方法内部过程
print(f.t)     # 调用方法内部过程取值
print(f.t)     # 调用方法内部过程取值

# 结果输出
# 运行test方法内部过程
# 3
# 3
# 运行t方法内部过程
# 44
# 运行t方法内部过程
# 44

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值