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

您的位置:首頁技術(shù)文章
文章詳情頁

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

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

問題描述

2017/2/6

描述

比如, 考慮這樣一段代碼, 它的執(zhí)行流程是怎樣的呢 ?

class Foo(object): @cached_property def foo(self):# calculate something important herereturn 42f = Foo()f.foof.foo 相關(guān)代碼

以class為基礎(chǔ)的緩存裝飾器

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上下文環(huán)境

產(chǎn)品版本: Python2

操作系統(tǒng): Linux

搜索

相似的問題: http://stackoverflow.com/ques...

問題解答

回答1:

cached_property 是 property 的subclass, 復(fù)寫了 __get__, __set__ 方法.

cached_property 是一個描述器(資料描述器),獲取屬性的時候優(yōu)先從描述器獲取,即(__get__).

所以執(zhí)行流程就是:f.foo -> __get__ -> 從實例字典(f.__dict__)獲取 -> 如果沒有則保存到字典并調(diào)用實際方法返回

回答2:

def cached_property(func): def _deco(*args, **kwargs):print(22222222222222)ret = func(*args, **kwargs) #這是調(diào)用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()

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 国产91在线 | 日韩 | 亚洲综合激情五月色播 | 久久亚洲国产成人精品性色 | 欧美日韩国产精品综合 | 国产91丝袜在线播放九色 | 国产剧情91| 一级毛片免费观看久 | 伊人久久综合影院 | 3级毛片 | 人体大胆做受免费视频 | 日韩欧美毛片免费看播放 | 国模午夜写真福利视频在线 | 美女大黄大色一级特级毛片 | 特级毛片a级毛免费播放 | 玖玖精品视频在线观看 | 91精品久久久久久久久中文字幕 | 国产一区日韩二区欧美三区 | 国产伦精品一区二区三区免费迷 | 国产精品第八页 | chinese老头 gay tube| 国产三级日本三级日产三 | 国产小视频在线观看www | 国产精品久久久久激情影院 | 中文字幕15页 | 免费色视频 | 日韩精品永久免费播放平台 | 亚洲 日本 欧美 日韩精品 | 99久久精品免费看国产免费 | 麻豆传媒免费入口 | 亚欧精品一区二区三区 | 国内精品网站 | 国产剧情网站 | 国产香蕉在线精彩视频 | 日本高清免费毛片久久看 | 国产精品久久久久久久久免费 | 国产在线精品一区二区三区不卡 | 亚洲欧美综合久久 | 国语一区| www.av在线.com| 国产免费叼嘿视频 | 色吊丝永久性观看网站大全 |