39 lines
1.2 KiB
Python
39 lines
1.2 KiB
Python
# 在之前的课程中,我们学会了给类的属性加property来让它们惰性求值
|
|
# 但是我们想要它求了一次以后就把值储存起来,下次调用就可以节省算力了
|
|
# 我们可以使用描述符类来完成这个操作
|
|
class lazyProperty:
|
|
def __init__(self, func):
|
|
self.func = func
|
|
|
|
def __get__(self, instance, cls):
|
|
if instance is None:
|
|
return self
|
|
else:
|
|
value = self.func(instance)
|
|
# 将原来类中的方法覆写删除,变成固定的数字
|
|
setattr(instance, self.func.__name__, value)
|
|
return value
|
|
|
|
# 我们可以这样使用它
|
|
import math
|
|
class Circle:
|
|
def __init__(self, radius):
|
|
self.radius = radius
|
|
|
|
@lazyProperty
|
|
def area(self):
|
|
print("computing area")
|
|
return math.pi * self.radius ** 2
|
|
|
|
@lazyProperty
|
|
def perimeter(self):
|
|
return 2 * self.radius
|
|
|
|
|
|
c = Circle(4)
|
|
print(c.area)
|
|
print(c.area)
|
|
|
|
# 这样相当于将实例中的方法替换为某个可替换的值,代价就是属性不再由计算得出,仅作为数据读取
|
|
# 这种方法可以用在一些只计算一次的实例上,来节省计算
|