Python, 这一个缓存装饰器, 其执行流程是怎样的?
问题描述
2017/2/6
描述比如, 考虑这样一段代码, 它的执行流程是怎样的呢 ?
class Foo(object): @cached_property def foo(self):# calculate something important herereturn 42f = Foo()f.foof.foo 相关代码
以class为基础的缓存装饰器
class cached_property(property): '''A decorator that converts a function into a lazy property. The function wrapped is called the first time to retrieve the result and then that calculated result is used the next time you access the value::class Foo(object): @cached_property def foo(self):# calculate something important herereturn 42 The class has to have a `__dict__` in order for this property to work. ''' # implementation detail: A subclass of python’s builtin property # decorator, we override __get__ to check for a cached value. If one # choses to invoke __get__ by hand the property will still work as # expected because the lookup logic is replicated in __get__ for # manual invocation. def __init__(self, func, name=None, doc=None):self.__name__ = name or func.__name__self.__module__ = func.__module__self.__doc__ = doc or func.__doc__self.func = func def __set__(self, obj, value):obj.__dict__[self.__name__] = value def __get__(self, obj, type=None):if obj is None: return selfvalue = obj.__dict__.get(self.__name__, _missing)if value is _missing: value = self.func(obj) obj.__dict__[self.__name__] = valuereturn value上下文环境
产品版本: Python2
操作系统: Linux
搜索相似的问题: http://stackoverflow.com/ques...
问题解答
回答1:cached_property 是 property 的subclass, 复写了 __get__, __set__ 方法.
cached_property 是一个描述器(资料描述器),获取属性的时候优先从描述器获取,即(__get__).
所以执行流程就是:f.foo -> __get__ -> 从实例字典(f.__dict__)获取 -> 如果没有则保存到字典并调用实际方法返回
回答2:def cached_property(func): def _deco(*args, **kwargs):print(22222222222222)ret = func(*args, **kwargs) #这是调用foo方法print(44444444444444)return ret return _decoclass Foo(object): def __init__(self):print (111111111111111111) @cached_property def foo(self):print(3333333333333)return 42f = Foo()f.foo()
相关文章:
1. python - 在bottle服务中创建定时器执行任务,为啥任务被重复执行,本应执行一次?2. python - django的代码,昨晚上还好好的,今天早上进不去管理界面了,怎么回事?谢谢。3. 请教: 关于 python 反斜杠转义的疑问4. python - 含中文JSON未能按期待进行dumps,(\xxx\xxx\xxx)?5. python - django 按日归档统计订单求解6. python - celery 如何解决worker和client代码同步问题7. python3的各种库的官方文档中文版在哪儿可以找到8. python - 关于matplotlib的x轴显示的问题9. python 计算两个时间相差的分钟数,超过一天时计算不对10. python - Pycharm一句代码写完可以自动补全空格么?
