python中的懒惰加载用途非常多,可以节省内存,其主要的思想就是延迟加载需要实例化的类。python是通过getattr和setattr实现的,代码和使用方法如下。
class Lazy(object):
def __init__(self, lazy_object, *args, **kwargs):
self.__dict__["_wrapper"] = None
self.__dict__["_wrapperobject"] = lazy_object
self.__dict__["args"] = args
self.__dict__["kwargs"] = kwargs
def __getattr__(self, item, *args, **kwargs):
if self._wrapper is None:
self.init_object()
if item in self.__dict__.keys():
return self.__dict__[item]
else:
return getattr(self._wrapper, item, *args, **kwargs)
def __setattr__(self, key, value):
if self._wrapper is None:
self.init_object()
setattr(self._wrapper, key, value)
def init_object(self):
self.__dict__['_wrapper'] = self._wrapperobject(*self.args, **self.kwargs)
class User:
def __init__(self, x):
print("10000")
self.name = x
self.age = 18
def get_text(self):
print(self.name)
user = Lazy(User, "libai")
user.get_text()