-
@cached_property
裝飾器使用單個self
參數作為屬性緩存方法的結果。隻要實例存在,緩存的結果就會一直存在,因此如果傳遞了實例並且隨後調用了函數,則將返回緩存的結果。考慮一個典型情況,在將模型實例放入上下文之前,視圖可能需要調用模型的方法來執行一些計算,其中模板可能會再次調用該方法:
# the model class Person(models.Model): def friends(self): # expensive computation ... return friends # in the view: if person.friends(): ...
在模板中,您將擁有:
{% for friend in person.friends %}
在這裏,
friends()
將被調用兩次。由於視圖中的實例person
和模板是一樣的,用@cached_property
裝飾friends()
方法可以避免這種情況:from django.utils.functional import cached_property class Person(models.Model): @cached_property def friends(self): ...
請注意,由於該方法現在是一個屬性,因此在 Python 代碼中需要適當地訪問它:
# in the view: if person.friends: ...
緩存的值可以視為實例的普通屬性:
# clear it, requiring re-computation next time it's called del person.friends # or delattr(person, "friends") # set a value manually, that will persist on the instance until cleared person.friends = ["Huckleberry Finn", "Tom Sawyer"]
由於說明符協議的工作方式,在尚未訪問的
cached_property
上使用del
(或delattr
)會引發AttributeError
。除了提供潛在的性能優勢之外,
@cached_property
還可以確保屬性的值在實例的生命周期內不會發生意外變化。這可能發生在計算基於datetime.now()
的方法上,或者如果在同一實例上後續調用方法之間的短暫間隔內某個其他進程將更改保存到數據庫中。您可以製作方法的緩存屬性。例如,如果您有一個昂貴的
get_friends()
方法並且希望允許在不檢索緩存值的情況下調用它,您可以編寫:friends = cached_property(get_friends)
雖然
person.get_friends()
將在每次調用時重新計算好友,但緩存屬性的值將持續存在,直到您將其刪除,如上所述:x = person.friends # calls first time y = person.get_friends() # calls again z = person.friends # does not call x is z # is True
本文介紹 django.utils.functional.cached_property
的用法。
聲明
class cached_property(func, name=None)[source]
相關用法
- Python Functools cached_property()用法及代碼示例
- Python calendar weekday()用法及代碼示例
- Python callable()用法及代碼示例
- Python calendar.HTMLCalendar用法及代碼示例
- Python calendar prmonth()用法及代碼示例
- Python calendar isleap()用法及代碼示例
- Python calendar setfirstweekday()用法及代碼示例
- Python string capwords()用法及代碼示例
- Python calendar leapdays()用法及代碼示例
- Python calendar month()用法及代碼示例
- Python calendar firstweekday()用法及代碼示例
- Python calendar weekheader()用法及代碼示例
- Python calendar calendar()用法及代碼示例
- Python calendar monthcalendar()用法及代碼示例
- Python calendar monthrange()用法及代碼示例
- Python calendar prcal()用法及代碼示例
- Python cudf.core.column.string.StringMethods.is_vowel用法及代碼示例
- Python cudf.Series.ceil用法及代碼示例
- Python cudf.core.column.string.StringMethods.endswith用法及代碼示例
- Python cuxfilter.charts.datashader.heatmap用法及代碼示例
- Python cusignal.windows.windows.hann用法及代碼示例
- Python cudf.DataFrame.isin用法及代碼示例
- Python cudf.core.column.string.StringMethods.title用法及代碼示例
- Python codecs.decode()用法及代碼示例
- Python cuml.metrics.pairwise_distances.pairwise_distances用法及代碼示例
注:本文由純淨天空篩選整理自djangoproject.com大神的英文原創作品 django.utils.functional.cached_property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。