亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

Python, 這一個緩存裝飾器, 其執行流程是怎樣的?

瀏覽:92日期:2022-09-23 11:24:40

問題描述

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()

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 久久亚洲天堂 | 国产精品99久久久久久宅男 | 一级黄色播放 | 麻豆传媒官网入口 | 色天天综合色天天害人害己 | 久久99热狠狠色一区二区 | 久久国产精品视频一区 | 国产制服丝袜在线 | ak福利午夜在线观看 | 欧美日韩1区 | 91香蕉福利一区二区三区 | 一区二区不卡免费视频 | 丁香婷婷亚洲六月综合色 | 亚洲性夜夜时 | 日韩伦理中文字幕 | 在线成人 | 高清精品美女在线播放 | 国产精品亚洲欧美 | 欧美久久亚洲精品 | 国产亚洲欧美在线人成aaaa | 肉色呻吟胯下丝袜高跟视频 | 欧美性大片免费 | 性色生活免费看性大片 | 伊人久久国产 | 黄色一级片免费观看 | 黄色片欧美 | 久久久久久a亚洲欧洲aⅴ | 一区二区三区免费在线 | 黄色免费毛片 | 爱爱欧美视频 | 亚洲一级毛片免费观看 | 91免费精品国偷自产在线在线 | 亚洲精品久久午夜香蕉 | 人人草人人干 | 91麻豆传传媒波多野衣久久看 | 亚洲图片欧洲图片aⅴ | 国产成人一区二区三区在线视频 | 欧美专区一区二区三区 | 精品国产999 | 久久免费精品视频在线观看 | 国产成人香蕉在线视频fuz |