当前位置:首页 > Python教程 > python技巧

Python进阶-----类的内置方法__getattribute__

__getattribute__ 方法功能:

1 调用属性会触发该功能,属性存在则会返回相应的值;
2 如果属性不存在则会抛出异常AttributeError,所以可以自定义异常信息
3 存在__getattr__,若有异常出现则会传递给__getattr__用来接收,执行操作

            class
             Foo:
    
            def
            __init__
            (self,x):
        self.x=x

    def__getattr__(self, item):
        print(执行的是我)
        # return self.__dict__[item]def__getattribute__(self, item):         #调取属性无论是否存在均会触发它print(不管是否存在,我都会执行)
        raise AttributeError(哈哈)          #其实就是python内部的处理方式
f1=Foo(10)
f1.x
f1.xxxxxx

#当__getattribute__与__getattr__同时存在,只会执行__getattrbute__,除非__getattribute__在执行过程中抛出异常AttributeError

 

原文:https://www.cnblogs.com/Meanwey/p/9788821.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!