Python 反射-isinstance
- 2020 年 1 月 19 日
- 筆記
用到的
isinstance(對象,類) ——————- 判斷一個對象是否是一個類的實例
issubclass(子類,父類) —————- 判斷一個類是否是一個類的子類
hasattr(對象,字元串屬性) ———— 判斷一個屬性在對象里有沒有
getattr(對象,屬性,第三參數) ——— 獲取對象中的字元串屬性
setattr(對象,屬性,值) —————— 屬性的賦值(設置值,修改值,新增值)
delattr(刪除的屬性) ——————– 刪除屬性操作
__str__ ———————————— 在對象被列印時自動觸發,可以用來定義對象被列印時的輸出資訊(必須返回一個字元串類型的值)
__del__ ———————————– 在對象被刪除時先自動觸發該方法,可以用來回收對象以外其他相關資源,比如系統資源
isinstance和issubclass例子
1 class Bar: 2 pass 3 4 5 class Foo(Bar): 6 pass 7 8 9 obj = Foo() 10 print(issubclass(Foo, Bar)) >>>True 11 print(isinstance(obj, Foo)) >>>True
反射例子
1 class Ftp: 2 def get(self): 3 print('get') 4 5 def put(self): 6 print('put') 7 8 def login(self): 9 print('login') 10 11 def run(self): 12 while True: 13 cmd = input('>>>: ').strip() # cmd='get' 14 if hasattr(self, cmd): 15 method = getattr(self, cmd) 16 method() 17 else: 18 print('輸入的方法不存在') 19 20 21 obj = Ftp() 22 obj.run()
__str__例子
在對象被列印時自動觸發,可以用來定義對象被列印時的輸出資訊(注意: 必須返回一個字元串類型的值)
1 class People: 2 def __init__(self, name, age): 3 self.name = name 4 self.age = age 5 6 def __str__(self): 7 return '<name:%s age:%s>' % (self.name, self.age) 8 9 10 obj = People('egon', 18) 11 print(obj) # print(obj.__str__()) >>><name:egon age:18>
__del__例子
在對象被刪除時先自動觸發該方法,可以用來回收對象以外其他相關資源,比如系統資源
1 class Foo: 2 def __init__(self, x, filepath, encoding='utf-8'): 3 self.x = x 4 self.f = open(filepath, 'rt', encoding=encoding) 5 6 def __del__(self): 7 print('run.....') 8 # 回收對象關聯的其他資源 9 self.f.close() 10 11 12 obj = Foo(1, 'a.txt') 13 print('主===========>') >>>主===========> >>>run.....