题目描述:
https://www.shiyanlou.com/challenges/3000
实现一个带 TTL 生存时间功能的属性装饰器。如果每次访问属性时间间隔小于 TTL,则返回相同的缓存值,但是访问间隔大于 TTL 时,则重新计算属性。
说一下做的时候遇到的几个问题:
1.instance是指ttl_property类自身
2.需要self.price = self._price,调用一次__set__
,设置初始时间和value
3.没有去尝试过挑战的测试用例。。因为不想改了
from time import time
class ttl_property(object):
def __init__(self, ttl=None):
self.ttl = ttl
def __call__(self, func):
self.func = func
return self
def __get__(self, instance, owner):
last_time = instance.__dict__['store'][1]
now = time()
if now > last_time + self.ttl:
value = self.func(instance)
instance.__dict__['store'] = (value, now)
return value
else:
return instance.__dict__['store'][0]
def __set__(self, instance, value):
instance.__dict__['store'] = (value, time())
class Book(object):
def __init__(self):
self._price = 100.0
self.price = self._price
@ttl_property(ttl=2)
def price(self):
self._price = self._price * 0.8
return self._price
测试:
>>> from ttl import Book
>>> b = Book()
>>> b.price
100.0