標籤:space ror 定製 error 自己 file trace 條件 lan
Python編程中raise可以實現報出錯誤的功能,而報錯的條件可以由程式員自己去定製。在物件導向編程中,可以先預留一個方法介面不實現,在其子類中實現。如果要求其子類一定要實現,不實現的時候會導致問題,那麼採用raise的方式就很好。而此時產生的問題分類是NotImplementedError。
寫一段代碼如下:
class ClassDemo:
def test_demo(self):
raiseNotImplementedError("my test: not implemented!")
classChildClass(ClassDemo):
pass
inst =ChildClass()
inst.test_demo()
程式運行結果:
E:\01_workspace\02_programme_language\03_python\OOP\2017\08\10>pythonerror_demo.py
Traceback (mostrecent call last):
File "error_demo.py", line 9, in<module>
inst.test_demo()
File "error_demo.py", line 3, intest_demo
raise NotImplementedError("my test:not implemented!")
NotImplementedError:my test: not implemented!
從上面的運行結果可以看出,程式識別到了這個方法並沒有在子類中實現卻被調用了。從代碼報錯的行數來看,只有這個子類的執行個體化對象調用相應的方法的時候才會報錯。這樣的推測結論也很容易通過代碼修改測試得到驗證,此處不再驗證。
進一步修改代碼:
class ClassDemo:
def test_demo(self):
raiseNotImplementedError("my test: not implemented!")
classChildClass(ClassDemo):
def test_demo(self):
print("OKOKOOK!")
inst =ChildClass()
inst.test_demo()
在新的代碼中,子類中實現了對test_demo方法的設計。程式的運行結果如下:
E:\01_workspace\02_programme_language\03_python\OOP\2017\08\10>pythonerror_demo.py
OKOKOOK!
從程式的執行結果可以看出,只要相應的方法介面進行了實現,在執行的時候未實施的錯誤便不會報出。
轉載:77074707
Python編程中NotImplementedError的使用