码迷,mamicode.com
首页 > 其他好文 > 详细

理解_getattr_方法

时间:2019-09-13 23:00:25      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:ati   att   except   ica   not   try   parse   理解   rgs   

  在学习rest framework的过程中,rest framework的request是经过重构的,但是如果调用重构对象request中的属性,如果属性不存在会调用原request对象中的属性,它使用的就是__getattr__方法。

class Request(object):
    """
    Wrapper allowing to enhance a standard `HttpRequest` instance.

    Kwargs:
        - request(HttpRequest). The original request instance.
        - parsers_classes(list/tuple). The parsers to use for parsing the
          request content.
        - authentication_classes(list/tuple). The authentications used to try
          authenticating the request‘s user.
    """
...

       def __getattr__(self, attr):
        """
        If an attribute does not exist on this instance, then we also attempt
        to proxy it to the underlying HttpRequest object.
        """
        try:
            return getattr(self._request, attr)
        except AttributeError:
            return self.__getattribute__(attr)
...

  在新构建的Request中存在__getattr__,假如调用request.GET,新构建的request中如果没有GET属性的话,就会调用__getattr__方法,并且将GET传递给__getattr__方法,此时返回的就是:

    getattr(self._request, GET)

总结:

  • _getattr__可以动态返回一个属性;
  • 当调用一个对象不存在的属性时,Python会试图调用该对象__getattr__(self,attr)方法

理解_getattr_方法

标签:ati   att   except   ica   not   try   parse   理解   rgs   

原文地址:https://www.cnblogs.com/shenjianping/p/11517607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!