Python反射、異常處理
阿新 • • 發佈:2017-08-20
onerror ini final index inpu 刪除 統一 異常處理 asa
反射
:字符串到對象屬性的映射
hasattr(obj,string),
判斷對象obj裏面是否有叫string的字段或方法
getattr(obj,string)
獲取obj對象裏名叫string的字段或方法(如果重名先找字段)
setattr(obj,y,v)
設置屬性或者方法obj.y = v
delattr(obj,y)
刪除屬性obj.y
class Dog(object): def __init__(self,name): self.name = name def eat(self): print("%s is eating"%self.name) d= Dog("labuladuo") choice = input(">>").strip() #用戶輸入什麽調用什麽方法,用反射 def bulk(self): print("%s is bulking"%self.name) if hasattr(d,choice): func = getattr(d,choice) func() #刪除屬性 delattr(d,choice) else: #動態添加一個方法d.choice = bulk setattr(d,choice,bulk) d.bulk(d)#動態添加一個屬性,如果該屬性存在會報錯 setattr(d,choice,None) print(getattr(d,choice))
反射為什麽重要?
動態的實現內存裝配,通過字符串反射到內存對象,不用寫一大堆if..else判斷用戶輸入什麽調用什麽方法了,直接用反射
異常處理
Python中有很多異常,有的異常不能通過編譯,例如:indentationError 這個不能catch
低級版:抓住全部錯誤。不要這樣用,自己搞著玩可以
try: names[3] data["name"] except Exception as e: print("出錯:",e)
正常版:預料一些錯誤。一般的使用方式
try: names[3] data["name"] except KeyError as e: print("沒有該key",e) except IndexError as e: print(e)
正常版低級形態:不知道是哪句代碼出錯,可以統一處理
try: names[3] data["name"] except (KeyError,IndexError) as e: print("錯誤",e)
終極出錯大套餐:基本考慮各種情況,但是Exception不能catch縮進異常
try: names[3] data["name"] open("aa.txt") except KeyError as e: print("沒有該key",e) except IndexError as e: print("下標越界",e) except Exception as e: print("未知錯誤:",e) else: print("一切正常") finally: print("不管有沒有錯,都執行")
自定義異常,例如別人調你的接口,別人觸發你定義的異常
Python反射、異常處理