属性描述符:实现了特定协议的类,这个协议包括 __get__、 __set__ 和 __delete__ 方法。描述符的用法是,创建一个实例,作为另一个类的类属性
import datetime
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):
print "Call __get__() funtion"
if instance is None:
return self
res = instance.__dict__[self.name] = self.func(instance)
return res
class User(object):
birth_year = 1988
@cached_property
def age(self):
return datetime.date.today().year - self.birth_year
u = User()
u.age
u.age
主要实现的功能是,u.age第一次会进行计算,计算完之后把实例u的__dict__['age']设置为计算后的值。下次读值的时候会直接从__dict__['age']取结果,避免了多次计算。
属性描述符请参考:http://blog.csdn.net/u011019726/article/details/78458336
实例属性遮盖参数:http://blog.csdn.net/u011019726/article/details/78423221
参考文档:https://www.the5fire.com/python-descriptor-example-in-django..html