你可以用
getattr
在单个序列化程序实例中:
def get_amount1(self,obj):
"""very large calculation here"""
if getattr(self, 'amount1', None):
return self.amount1
self.amount1 = 5
return self.amount1
def get_amount2(self,obj):
"""very large calculation here"""
if getattr(self, 'amount2', None):
return self.amount2
self.amount2 = 10
return self.amount2
def get_amount3(self,obj):
"""very large calculation here"""
if getattr(self, 'amount3', None):
return self.amount3
self.amount3 = 15
return self.amount4
def get_total(self,obj):
return self.get_amount1(obj) +self.get_amount2(obj)+self.get_amount3(obj)
或者正如@Willem Van Onsem在评论中提到的那样
lru_cache
对于更广泛的缓存:
@lru_cache
def get_amount1(self,obj):
"""very large calculation here"""
return 5
@lru_cache
def get_amount2(self,obj):
"""very large calculation here"""
return 10
@lru_cache
def get_amount3(self,obj):
"""very large calculation here"""
return 15