执行流程:
全局属性request对象:
request = LocalProxy(partial(_lookup_req_object, "request"))
# request添加属性:
# self._LocalProxy__local=partial(_lookup_req_object, "request")
# self.__wrapped__=partial(_lookup_req_object, "request")
1. request.method执行流程:
request = LocalProxy(partial(_lookup_req_object, "request"))
request.method = LocalProxy(partial(_lookup_req_object, "request")).method
2. 执行request对象__getattr__方法, 最终得到:partial(_lookup_req_object, "request").method
def __getattr__(self, name): # name=method
if name == "__members__":
return dir(self._get_current_object())
# getattr(self._get_current_object(), 'method'), self=LocalProxy对象
# 即self._get_current_object() = partial(_lookup_req_object, "request")
# 故:getattr(self._get_current_object(), 'method') = partial(_lookup_req_object, "request").method
return getattr(self._get_current_object(), name)
def _get_current_object(self):
"""Return the current object. This is useful if you want the real
object behind the proxy at a time for performance reasons or because
you want to pass the object into a different context.
"""
if not hasattr(self.__local, "__release_local__"):
# self.__local = partial(_lookup_req_object, "request")
return self.__local()
try:
return getattr(self.__local, self.__name__) # 在初始化的时候:object.__setattr__(self, "_LocalProxy__local", local)
except AttributeError:
raise RuntimeError("no object bound to %s" % self.__name__)
3. 最终执行partial(_lookup_req_object, "request").method
partial(_lookup_req_object, "request").method = partial(_lookup_req_object, "request").method = _lookup_req_object("request").method
本质上是执行:_lookup_req_object("request").method
_lookup_req_object("request") 返回上下文request对象(线程安全), 该request对象包含method属性
def _lookup_req_object(name): # name="request"
# 获取上下文self._local.stack[-1]--(线程id/协程内存地址标识)
top = _request_ctx_stack.top
if top is None:
raise RuntimeError(_request_ctx_err_msg)
# 等价于:self._local.stack[-1].request获取到request对象
return getattr(top, name)
私有属性的定义与获取:
class A(object):
def __init__(self):
# 类内部定义私有属性的三种方式
object.__setattr__(self, '_A__gender', 'male')
self._A__name = 'wyq'
self.__age = 28
def __call__(self, *args, **kwargs):
# 类内部获取私有属性
print(self.__name)
print(self._A__name)
print(self.__age)
print(self._A__age)
print(self.__gender)
print(self._A__gender)
a = A()
a()
# 类外部获取私有属性
print(a._A__name)
print(a._A__age)
print(a._A__gender)