3

看着django.utils.functional我注意到一个LazyObject类,django 使用它django.conf

class LazySettings(LazyObject):

它是 的定义LazyObject

class LazyObject(object):
    """
    A wrapper for another class that can be used to delay instantiation of the
    wrapped class.

    By subclassing, you have the opportunity to intercept and alter the
    instantiation. If you don't need to do that, use SimpleLazyObject.
    """
    def __init__(self):
        self._wrapped = None

    def __getattr__(self, name):
        if self._wrapped is None:
            self._setup()
        return getattr(self._wrapped, name)

    def __setattr__(self, name, value):
        if name == "_wrapped":
            # Assign to __dict__ to avoid infinite __setattr__ loops.
            self.__dict__["_wrapped"] = value
        else:
            if self._wrapped is None:
                self._setup()
            setattr(self._wrapped, name, value)

    def __delattr__(self, name):
        if name == "_wrapped":
            raise TypeError("can't delete _wrapped.")
        if self._wrapped is None:
            self._setup()
        delattr(self._wrapped, name)

    def _setup(self):
        """
        Must be implemented by subclasses to initialise the wrapped object.
        """
        raise NotImplementedError

    # introspection support:
    __members__ = property(lambda self: self.__dir__())

    def __dir__(self):
        if self._wrapped is None:
            self._setup()
        return  dir(self._wrapped)

我想知道使用的最佳情况是LazyObject什么?

4

1 回答 1

1

它基于 exp。据我所知:
1. 获取一个数据,你现在不使用它并且仍然操作它,就像 django 中的 QuerySet
2. 你可以告诉现在在哪里加载/读取它的数据,比如配置。
3. 代理
4. 大量数据,现在只使用其中的一部分。
和更多...

于 2012-10-27T03:07:47.523 回答