對某個屬性進行訪問的時候,不需要經過反復的計算再回傳
對屬性的首次訪問,將其值快取起來,在其后的訪問中,直接從快取中取值,主要用來提高程式的性能
""" 屬性惰性求值 這里介入描述符就可以實作 """ class LazyProperty: def __init__(self, func): self.func = func def __get__(self, instance, owner): if instance is None: return self value = self.func(instance) setattr(instance, self.func.__name__, value) return value class Valley: @LazyProperty def age(self): print("shi_xiao_gu_a") return 2 * 13 v = Valley() print(v.age) print(v.age)
output:
shi_xiao_gu_a
26
26
可見文本內容只列印了一次
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/553053.html
標籤:Python
上一篇:【pandas基礎】--資料排序
下一篇:返回列表
