Python進階-----類的內置方法__getattribute__
阿新 • • 發佈:2018-10-15
拋出異常 elf 方法 內置 def style spa print get 1 調用屬性會觸發該功能,屬性存在則會返回相應的值;
__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
Python進階-----類的內置方法__getattribute__