您好,登錄后才能下訂單哦!
小編給大家分享一下python3中的cached_property函數(shù)怎么用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!
這個函數(shù)與property()類似,但增加了緩存,對于計(jì)算復(fù)雜的屬性很有用。
舉例如下:
# 在沒有cached_property之前定義類屬性 class DataSet: def __init__(self): self._data = None @property def data(self): print('開始計(jì)算數(shù)據(jù)') if not self._data: # 計(jì)算data數(shù)據(jù) self._data = 10 * 10 print('計(jì)算data數(shù)據(jù)') return self._data obj = DataSet() print(obj.data) # 輸出 開始計(jì)算數(shù)據(jù) 計(jì)算data數(shù)據(jù) 100 print(obj.data) # 輸出 開始計(jì)算數(shù)據(jù) 100
使用變量記錄屬性數(shù)據(jù),并在屬性計(jì)算是進(jìn)行判斷,防止計(jì)算多次
from functools import cached_property class DataSet: @cached_property def data(self): print('開始計(jì)算數(shù)據(jù)') return 10 * 10 obj = DataSet() print(obj.data) # 輸出: 開始計(jì)算數(shù)據(jù) 100 print(obj.data) # 輸出: 100
注意:不支持python中的異步編程:asyncio。
以上是python3中的cached_property函數(shù)怎么用的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對大家有所幫助,如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。