python @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): 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
复制代码

不使用的例子:

复制代码
class User(object):
    def __init__(self, age=0):
        self.age=age
    
    def getWorkYear(self):
        return 65-self.age


user=User(20)
print(user.getWorkYear)     #<bound method User.getWorkYear of <__main__.User object at 0x00000000031A3C88>>
print(user.getWorkYear())   #45
print(user.__dict__)  #{'age': 20}
print(user.getWorkYear) #<bound method User.getWorkYear of <__main__.User object at 0x00000000031A3C88>>
复制代码

使用的例子:

复制代码
from django.utils.functional import cached_property

class User(object):
    def __init__(self, age=0):
        self.age=age

    @cached_property
    def getWorkYear(self):
        return 65-self.age


user=User(20)
print(user.getWorkYear)    #45
print(user.getWorkYear())  #error
print(user.__dict__)  #{'age': 20, 'getWorkYear': 45}
print(user.getWorkYear) #45
复制代码

cached_property主要实现的功能是,user.getWorkYear第一次会进行计算,计算完之后把实例user的__dict__['getWorkYear']设置为计算后的值。下次读值的时候会直接从__dict__['getWorkYear']取结果,避免了多次计算。
使用限制:只能用于只带默认参数的类

user.getWorkYear -> __get__ -> 从实例字典(user.dict`获取 -> 如果没有则保存到字典并调用实际方法返回

posted on   不要挡着我晒太阳  阅读(851)  评论(0编辑  收藏  举报

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· winform 绘制太阳,地球,月球 运作规律
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示