利用描述符自定制property
class Lazyproperty:
def __init__(self,func):
# print('==========>',func)
self.func=func
def __get__(self, instance, owner): #只有get的情况下是非数据描述符,优先级比实例的低
print('get')
# print(instance)
# print(owner)
if instance is None: #实例调用的时候穿的是自己 类屌的时候传的是none
return self
res=self.func(instance)
setattr(instance,self.func.__name__,res)#这样在非数据描述符的情况下可以实现缓存懒加载的效果,因为实例数据的优先级高于非数据描述符
return res
# def __set__(self, instance, value):#加上__set__后变成了数据描述符,才是数据描述符优先级只低于类,高于实例,这时候就会失去上述的懒加载效果,每次都从数据描述符中查找数据。
# pass class Room:
def __init__(self,name,width,length):
self.name=name
self.width=width
self.length=length
# @property #area=property(area)
@Lazyproperty #area=Lazypropery(area)
def area(self):
return self.width * self.length
@property #test=property(test)
def area1(self):
return self.width * self.length
# print(Room.__dict__)
r1=Room('厕所',1,1)
# print(r1.__dict__) #实例调用
# print(r1.area)
# print(Room.__dict__) #类调用
# print(Room.area) # print(r1.test)
# print(Room.test)
# print(r1.area1)
# print(r1.area1)
# print(r1.area1)
# print(r1.area1) print(r1.area)
print(r1.__dict__) print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)
print(r1.area)