python面对对象(getattr(),__getattr__(),__getattribute__()方法的区别)

getattr() 为 函数,而__getattr__(), __getattribute__()为类的方法

1. getattr() 参数为 (object,attr_name,default value) 会调用该object的__getattribute__()方法,如果没有返回值,继续调用__getattr__()方法

2. 任何调用实例的属性值,都会调用到__getattribute__方法,如果没有返回值会继续调用__getattr__(),也就是__getattr__() 相当于exception机制,不一定会被调用

示例:

class demo(object):
    def __init__(self):
        self.a = 10

    def __getattribute__(self, item):
        print("__getattribute__ is called ")
        return super(demo, self).__getattribute__(item)

    def __getattr__(self, item):
        print("__getattr__ is called")
        return item


if __name__ == '__main__':
    d = demo()
    # print(d.a)
    # print(d.b)
    print(getattr(d, "a"))
    print(getattr(d, "b"))


# 答案:
__getattribute__ is called 
10
__getattribute__ is called 
__getattr__ is called
b

 restful中request二次封装获取原始_request对象属性与获取当前封装后的request对象属性定义源码示例:

    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)  

 

posted @ 2019-09-08 11:35  WiseAdministrator  阅读(326)  评论(0编辑  收藏  举报