帶緩存功能的property
my_property
class my_property:
def __init__(self, fget=None, fset=None, fdel=None, cache=False):
self.fget = fget
self.fset = fset
self.fdel = fdel
self.cache = cache
def setter(self, func):
if self.cache:
raise ValueError("'setter' require cache is False")
if self.fget is None:
raise ValueError("descriptor 'setter' requires a 'property' object but received a 'function'")
self.fset = func
def deleter(self, func):
if self.fget is None and self.fset is None:
raise ValueError("TypeError: descriptor 'deleter' requires a 'property' object but received a 'function'")
self.fdel = func
def __get__(self, instance, owner):
if instance is None:
return self
value = self.fget(instance)
if self.cache:
instance.__dict__[self.fget.__name__] = value
return value
def __call__(self, func):
self.fget = func
return self
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@my_property(cache=True)
def area(self):
print('============計算面積啦============')
return self.width*self.height
@my_property
def perimeter(self):
print('------------計算周長啦------------')
return (self.width + self.height) * 2
a = Rectangle(3, 4)
print(a.area)
print(a.area)
print(a.perimeter)
print(a.perimeter)
結果如下
/usr/bin/python3.6 /home/sunsong/Desktop/Demo/C.py
============計算面積啦============
12
12
------------計算周長啦------------
14
------------計算周長啦------------
14
可以看到設置緩存的沒有進行第二次計算,而沒有設置緩存的進行了兩次計算。