python學習-NotImplementedError的使用


謹以此文,記錄自己在學習python過程中遇到的問題和知識點。如有錯漏,還請各位朋友指正,感謝!

問題簡述

在python中,raise可以實現報出錯誤的功能,而報出錯誤的條件是程序員可以自己規定的。在面向對象編程中,如果想在父類中預留一個方法,使該方法在子類中實現。如果子類中沒有對該方法進行重寫就被調用,則報NotImplementError這個錯誤。

代碼理解

如下面代碼所示,子類Two中沒有重寫父類One中的show方法,就對其進行了調用:

class One(object):
    
    def show(self):
        raise NotImplementedError

class Two(One):
    
    def show_of_two(self):
        print('hello world!')

number = Two()
number.show()

運行上述代碼的結果如下:(報出NotImplementedError)

Traceback (most recent call last):
  File "c:/Users/Sykai/Desktop/PyLearn/test.py", line 20, in <module>
    number.show()
  File "c:/Users/Sykai/Desktop/PyLearn/test.py", line 12, in show
    raise NotImplementedError
NotImplementedError

正確使用方法應該如下所示:

class One(object):
    
    def show(self):
        raise NotImplementedError

class Two(One):
    
    def show(self):
        print('hello world!')

number = Two()
number.show()

運行代碼輸出結果:

hello world!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM