gpt4 book ai didi

python - 在 python 或 django 中使用 lazyobject

转载 作者:行者123 更新时间:2023-11-28 18:51:04 27 4
gpt4 key购买 nike

查看 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 的最佳情况是什么?

最佳答案

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

关于python - 在 python 或 django 中使用 lazyobject,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13096855/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com