Python中NotImplementedError的使用方法抽象类集成子类实现

写一段代码如下:

class ClassDemo:
    def test_demo(self):
           raise NotImplementedError("my test: not implemented!")
  
class ChildClass(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):
           raise NotImplementedError("my test: not implemented!")
  
class ChildClass(ClassDemo):
    def test_demo(self):
       print("OK OK OOK!")
  
inst = ChildClass()
inst.test_demo()

在新的代码中,子类中实现了对test_demo方法的设计。

程序的运行结果如下:

E:\01_workspace\02_programme_language\03_python\OOP\2017\08\10>pythonerror_demo.py
OKOKOOK!

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

 

开源代码常如此使用

class ServiceLoader(object,Metaclass=RegisterClasses):
    @classmethod
    def start(cls,addr,iface=None):
        raise NotImplementedError("do it")

    @classmethod
    def stop(cls,daemon):
        daemon.close()

 

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...