懒加载代理模式
2018-12-21 本文已影响0人
sunshining小迪儿
正常加载初始化实例
import time
class Test:
def __init__(self):
self.x = 'foo'
self.y = 'bar'
self._resource = self.resource()
def resource(self):
# 初始化中耗时操作
print('初始化属性_resource......耗时5秒')
time.sleep(5)
_ = tuple(range(5))
return _
if __name__ == '__main__':
t = Test()
print(t.x)
print(t.y)
print(t._resource)
输出结果:
初始化属性_resource......
foo
bar
(0, 1, 2, 3, 4)
在实例初始化后需要调用属性再加载
import time
class LazyProperty:
def __init__(self, method):
print('LazyProperty')
self.method = method
self.method_name = method.__name__
def __get__(self, instance, owner):
if not instance: # 类调用
return None
value = self.method(instance)
if __name__ == '__main__': # 在主模块调用时每个实例有一个副本
setattr(instance.__class__, self.method_name, value)
else: # 被其他模块调用时每个实例共用一个副本
setattr(instance,self.method_name,value)
return value
class Test:
def __init__(self):
self.x = 'foo'
self.y = 'bar'
self._resource = None
@LazyProperty # init_resource =LazyProperty(init_resource) 调用属性时执行__get__
def init_resource(self):
# 初始化中耗时操作
print('初始化属性_resource......')
time.sleep(5)
self._resource = tuple(range(5))
return self._resource
if __name__ == '__main__':
t = Test()
print(t.x)
print(t.y)
print(Test.init_resource) # 类调用类属性时不会初始化返回None
print(t.init_resource) # 初始化返回初始化结果
print(t._resource)
输出结果:
LazyProperty
foo
bar
None
初始化属性_resource......耗时5秒
(0, 1, 2, 3, 4)
(0, 1, 2, 3, 4)