【发布时间】:2020-06-26 17:24:30
【问题描述】:
我很好奇werkzeug 包中的LocalProxy 是如何工作的。具体来说,__local字段在哪里初始化?
@implements_bool
class LocalProxy(object):
__slots__ = ("__local", "__dict__", "__name__", "__wrapped__")
def __init__(self, local, name=None):
object.__setattr__(self, "_LocalProxy__local", local)
object.__setattr__(self, "__name__", name)
if callable(local) and not hasattr(local, "__release_local__"):
object.__setattr__(self, "__wrapped__", local)
def _get_current_object(self):
if not hasattr(self.__local, "__release_local__"):
return self.__local()
try:
return getattr(self.__local, self.__name__)
except AttributeError:
raise RuntimeError("no object bound to %s" % self.__name__)
...
LocalProxy 类定义中没有其他地方引用self.__local,在我看来self.__local 没有在任何地方初始化。它是否以某种方式神奇地别名为self._LocalProxy__local?
【问题讨论】:
-
设置在
__init__的第一行,即object.__setattr__(self, "_LocalProxy__local", local)。