#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""对比__getattribute__、__getattr__、__getitem__函数的区别"""

class AboutAttr(dict):
    def __init__(self, name):
        self.name = name
        self.dict = {}

    def __getattribute__(self, item):
        print("in __getattribute__ key:%s"%item)
        try:
            return super(AboutAttr, self).__getattribute__(item)
        except KeyError:
            #这里不会触发
            print("KeyError:%s"%item)
            raise
        except AttributeError:
            #当属性不存在时
            print("AttributeError:%s"%item)
            raise

    def test(self):
        print("test")

    def __getattr__(self, item):
        #当没有改属性时(即__getattribute__报错时),调用当前函数
        print("in __getattr__ key:%s"%item)
        #return self.dict[item] #通过hasattr判断不存在的键能正常返回false,也就是报错的时候才返回False
        return self.dict.get(item, None) #通过hasattr判断的不存在的也会返回true,

    def __getitem__(self, item):
        print("in __getitem__ key:%s"%item)
        return super(AboutAttr, self).__getitem__(item)

    def __setitem__(self, key, value):
        #如果基类不是dict之类的对象,则调用super里面的__setitem__会报错
        print("in __setitem__ key:%s, value:%s"%(key, value))
        return super(AboutAttr, self).__setitem__(key, value)

if __name__=="__main__":
    a = AboutAttr("a")
    print a.get("name") #对应的调用__getitem__
    print a.name
    #print a.not_exists
    a["t"] = "t"
    print a["t"]
    print a.test
    print a.test()
    print getattr(a, "test")
    print getattr(a, "name")
    print hasattr(a, "nnn")

"""打印结果
in __getattribute__ key:get
None
in __getattribute__ key:name
a
in __setitem__ key:t, value:t
in __getitem__ key:t
t
in __getattribute__ key:test
<bound method AboutAttr.test of {'t': 't'}>
in __getattribute__ key:test
test
None
in __getattribute__ key:test
<bound method AboutAttr.test of {'t': 't'}>
in __getattribute__ key:name
a
in __getattribute__ key:nnn
AttributeError:nnn
in __getattr__ key:nnn
in __getattribute__ key:dict
True 
"""


Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐