2012-10-27 67 views
3

django.utils.functional找我注意到一個LazyObject類,Django使用它django.conf使用lazyobject在Python或Django的

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

這就像力量。當你需要它時,你會知道的。 – dokkaebi

回答

1

它基於exp。據我所知:
1.獲取一個數據,你現在不使用它,並仍然使用它,如Django的QuerySet
2.數據你可以告訴現在加載/讀取它,比如配置。
3.代理
4.大量數據,現在就使用它的一部分。
和更多...

+0

你能告訴我這個細節的優越性嗎? – gnemoug

+0

1. queryset,你不知道當時會得到什麼數據,例如:uses = User.object.all()和u使用分頁,真正的數據不是全部(),它就像過濾器(id__gt = xx ,id__lt = XX)。 2.配置文件可以在運行時動態解析,不知道什麼時候不用。 3.它是代理設計模式。 4.一次加載大量數據真的很慢,所以你需要一次加載一部分,像sql,一次結果行。 – xfx