Python编程中NotImplementedError的使用方法

yipeiwu_com6年前Python基础

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!

从程序的执行结果可以看出,只要相应的方法接口进行了实现,在执行的时候未实施的错误便不会报出。

以上这篇Python编程中NotImplementedError的使用方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

浅谈python中的面向对象和类的基本语法

浅谈python中的面向对象和类的基本语法

当我发现要写python的面向对象的时候,我是踌躇满面,坐立不安呀。我一直在想:这个坑应该怎么爬?因为python中关于面向对象的内容很多,如果要讲透,最好是用面向对象的思想重新学一遍前...

Python安装官方whl包和tar.gz包的方法(推荐)

Windows环境:   安装whl包:pip install wheel    ->    pip install&n...

django框架模板中定义变量(set variable in django template)的方法分析

本文实例讲述了django框架模板中定义变量的方法。分享给大家供大家参考,具体如下: 总有一些情况,你会想在django template中设置临时变量,但是django 对在模板中对临...

pytorch 加载(.pth)格式的模型实例

pytorch 加载(.pth)格式的模型实例

有一些非常流行的网络如 resnet、squeezenet、densenet等在pytorch里面都有,包括网络结构和训练好的模型。 pytorch自带模型网址:https://pyto...

python采集微信公众号文章

python采集微信公众号文章

本文实例为大家分享了python采集微信公众号文章的具体代码,供大家参考,具体内容如下 在python一个子目录里存2个文件,分别是:采集公众号文章.py和config.py。 代码如下...