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!
原文地址:https://www.cnblogs.com/sykline/p/14630854.html