python中的懶惰加載問題(延遲加載)

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()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章