python基礎-面向物件(十三)面向物件進階(一):匯入py檔案自己,isinstance(obj,cls),issubclass(sub,super),__getattribute__
阿新 • • 發佈:2020-12-14
1.匯入py檔案自己
x = 1 y = 2 import main as ojx #直接匯入自己檔名 print('==>', hasattr(ojx, 'x'))
x = 1 y = 2 import sys obj1 = sys.modules[__name__] print('==>', hasattr(obj1, 'x'))
2.isinstance(obj,cls)-是否是cls(或繼承自cls的類)例項出來的物件
3.issubclass(sub,super)-是否是子類
4.__getattribute__
前面學過getattr(obj,item)獲取屬性,
__getattr__屬性不存在的時候呼叫,
現在又來個__getattribute__,又是幹啥的呢。
class Test: def __init__(self, name): self.name = name def __getattr__(self, item): print('from __getattr__') def __getattribute__(self, item): print('from __getattribute') test1 = Test('蒼老師') test1.name test1.age
呼叫存在的name屬性和不存在的age屬性,都會呼叫__getattribute__。沒有呼叫__getattr__,什麼時候呼叫呢?
class Test: def __init__(self, name): self.name = name def __getattr__(self, item): #接住AttributeError異常 print('from __getattr__') def __getattribute__(self, item): print('from __getattribute') raise AttributeError('小弟,接著異常') #丟擲異常 test1 = Test('蒼老師') test1.name test1.age
執行的流程:
丟擲異常後面要學,這裡不必深究。