[python]@cached_property缓存装饰器
2024-09-03 04:44:17
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
cached_property
主要实现的功能是,user.getWorkYear
第一次会进行计算,计算完之后把实例user的__dict__['getWorkYear']
设置为计算后的值。下次读值的时候会直接从__dict__['getWorkYear']
取结果,避免了多次计算。
使用限制:只能用于只带默认参数的类
不使用的例子
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
user.getWorkYear
-> __get__
-> 从实例字典(user.dict`获取 -> 如果没有则保存到字典并调用实际方法返回
最新文章
- php字符串格式化函数addslashes()
- 设置表格td宽度
- 一点一滴之NHibernate
- GNU的ar,ranlib和nm
- GitLab CI
- android之PackageManager简单介绍
- Redis进阶实践之三如何在Windows系统上安装安装Redis
- 计蒜客NOIP2017提高组模拟赛(三)day1
- 题解 P2763 【试题库问题】
- 从.Net到Java学习第五篇——Spring Boot &;&;Profile &;&;Swagger2
- 莫名奇妙虚拟机 ip addr 不显示 ip 地址,连不上网络
- Ant将Jmeter的jtl文件转为html文件报“前言中不允许有内容”
- Layui 写一个简单的后台页面
- python之字符串常用的方法
- centos7 下通过yum安装JDK
- Integer包装类源码分析
- [T-ARA][놀아볼래?][要玩吗]
- 【http学习杂记】2017年7月14日
- System.out.print实现原理猜解
- Java网络编程学习A轮_05_Socket编程
热门文章
- 如何理解归一化(Normalization)对于神经网络(深度学习)的帮助?
- 在Windows中 , 如何用leakdiag “自动”检测内存泄露 (自动记录日志)
- pycharm 报错 ModuleNotFoundError: No module named &#39;distutils.core&#39;
- 关于一些JS的运算符
- 解决 vue 使用 element 时报错ERROR in ./node_modules/element-ui/lib/theme-chalk/fonts/element-icons.ttf
- 8.JSP与JavaBean
- PHP中RabbitMQ之amqp扩展实现(四)
- php-amqplib库操作RabbitMQ
- C# 修改Config文件,增删查改
- 【Day3】5.Python中的lxml模块