Python, 這一個(gè)緩存裝飾器, 其執(zhí)行流程是怎樣的?
問(wèn)題描述
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
搜索相似的問(wèn)題: http://stackoverflow.com/ques...
問(wèn)題解答
回答1:cached_property 是 property 的subclass, 復(fù)寫了 __get__, __set__ 方法.
cached_property 是一個(gè)描述器(資料描述器),獲取屬性的時(shí)候優(yōu)先從描述器獲取,即(__get__).
所以執(zhí)行流程就是:f.foo -> __get__ -> 從實(shí)例字典(f.__dict__)獲取 -> 如果沒(méi)有則保存到字典并調(diào)用實(shí)際方法返回
回答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()
相關(guān)文章:
1. python - 求助,ValueError: View function did not return a response2. python - 小白django提交數(shù)據(jù)后,沒(méi)有存儲(chǔ)到數(shù)據(jù)庫(kù)(查閱資料并沒(méi)有發(fā)現(xiàn)問(wèn)題)3. nginx - pip install python庫(kù)報(bào)錯(cuò)4. python - Django怎么獲取數(shù)據(jù)庫(kù)的值,并放到一起輸出5. 網(wǎng)頁(yè)爬蟲(chóng) - python requests爬蟲(chóng),如何post payload6. python 計(jì)算兩個(gè)時(shí)間相差的分鐘數(shù),超過(guò)一天時(shí)計(jì)算不對(duì)7. python - HTML中的img標(biāo)簽,如何在request.args里找到img標(biāo)簽屬性?8. Python使用graphviz畫流程圖過(guò)程解析9. python - 關(guān)于爬蟲(chóng)爬取圖片的問(wèn)題?10. python - Push Notification推送服務(wù)在手機(jī)上測(cè)試時(shí)候無(wú)法收到生產(chǎn)環(huán)境的推送
