Python編程中NotImplementedError的使用

來源:互聯網
上載者:User

標籤: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的使用

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.