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`获取 -> 如果没有则保存到字典并调用实际方法返回

最新文章

  1. php字符串格式化函数addslashes()
  2. 设置表格td宽度
  3. 一点一滴之NHibernate
  4. GNU的ar,ranlib和nm
  5. GitLab CI
  6. android之PackageManager简单介绍
  7. Redis进阶实践之三如何在Windows系统上安装安装Redis
  8. 计蒜客NOIP2017提高组模拟赛(三)day1
  9. 题解 P2763 【试题库问题】
  10. 从.Net到Java学习第五篇——Spring Boot &amp;&amp;Profile &amp;&amp;Swagger2
  11. 莫名奇妙虚拟机 ip addr 不显示 ip 地址,连不上网络
  12. Ant将Jmeter的jtl文件转为html文件报“前言中不允许有内容”
  13. Layui 写一个简单的后台页面
  14. python之字符串常用的方法
  15. centos7 下通过yum安装JDK
  16. Integer包装类源码分析
  17. [T-ARA][놀아볼래?][要玩吗]
  18. 【http学习杂记】2017年7月14日
  19. System.out.print实现原理猜解
  20. Java网络编程学习A轮_05_Socket编程

热门文章

  1. 如何理解归一化(Normalization)对于神经网络(深度学习)的帮助?
  2. 在Windows中 , 如何用leakdiag “自动”检测内存泄露 (自动记录日志)
  3. pycharm 报错 ModuleNotFoundError: No module named &#39;distutils.core&#39;
  4. 关于一些JS的运算符
  5. 解决 vue 使用 element 时报错ERROR in ./node_modules/element-ui/lib/theme-chalk/fonts/element-icons.ttf
  6. 8.JSP与JavaBean
  7. PHP中RabbitMQ之amqp扩展实现(四)
  8. php-amqplib库操作RabbitMQ
  9. C# 修改Config文件,增删查改
  10. 【Day3】5.Python中的lxml模块