python调用拦截,属性字段

使用__getattribute__方法,针对类中的属性方法都会拦截
这个感觉和Java中的拦截器的意思一样,但是这个更简单一些;

class GetAttriBute:

    def __getattribute__(self, item):
        print("拦截前"+item);
        # 加下行代码即可放行
        return object.__getattribute__(self, item);

    def testGetAttriBute(self):
        print("来调我呀");

def main():
    getAttriBute = GetAttriBute();
    getAttriBute.testGetAttriBute();

if __name__ == '__main__':
    main();

周六日休息了两天啥也没干,周一来了就处理报障,搞得现在才能摸鱼学python;

实例属性字典

class Message():
    def __init__(self,note):
        self.note = note;

    def remove_note(self):
        del self.note;

    def get_note(self):
        return self.note;

    def __setattr__(self, key, value):
        print("setAttr key = {},value = {}".format(key,value));
        # 如果这里使用了这个方法,那么必须明确的使用dict这个方法,将属性保存在其中
        self.__dict__[key] = value;

    def __getattr__(self, item):
        print("getAttr item = {}".format(item));
        # 当属性不存在的时候会调用这个方法;
        return "属性不存在";

    def __delattr__(self, item):
        print("delattr item = {}".format(item));
        # 从字典里面删除属性
        self.__dict__.pop(item);

def main():
    msg = Message("www.baidu.com");
    print("获取存在的属性 {}".format(msg.get_note()));
    print("获取不存在的属性 {}".format(msg.contant));
    msg.remove_note();

if __name__ == '__main__':
    main();

猜你喜欢

转载自blog.csdn.net/weixin_44887276/article/details/114529782