微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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()

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐