国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

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

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

瀏覽:100日期: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 編程
相關文章:
主站蜘蛛池模板: 成人男女网18免费看 | 一二三中文乱码亚洲乱码 | 久久精品视频网站 | 亚洲高清视频在线 | 免费一级特黄3大片视频 | 人人99 | 国产精品青草久久久久福利99 | chinese耄耋70老太性 | 国产一区二区三区久久 | 综合九九 | 亚洲精品成人久久 | 岛国片欧美一级毛片 | 欧美一级特黄aaaaaa在线看首页 | 久久极品视频 | 久久91精品国产一区二区 | 偷拍精品视频一区二区三区 | 日本精品视频一区二区三区 | 亚州不卡 | 成人国产永久福利看片 | 亚洲碰碰 | 欧美成人吃奶高清视频 | 国产猛烈无遮掩视频免费网站男女 | 在线黄网 | 女人张开双腿让男人桶爽免 | 亚洲第一成年网 | 亚洲美女影院 | 国内精品中文字幕 | 久久久免费观成人影院 | 在线男人天堂 | 国产高清在线精品一区a | 另类视频在线 | 亚洲第一在线 | 久久2| 一区二区三区精品国产欧美 | 一个人看的www片免费视频中文 | 国产玖玖在线 | jizjizjiz亚洲人| 免费一级毛片女人图片 | 成 人 动漫在线观看网站网站 | 久久黄色影片 | 午夜性爽爽爽 |