欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

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

发布时间:2025/3/15 python 34 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Python中NotImplementedError的使用方法(抽象类集成子类实现) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

写一段代码如下:

class ClassDemo:def test_demo(self):raise NotImplementedError("my test: not implemented!")class ChildClass(ClassDemo):passinst = 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_demoraise 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):@classmethoddef start(cls, addr, iface=None):raise NotImplementedError("do it")@classmethoddef stop(cls, daemon):daemon.close()

 

总结

以上是生活随笔为你收集整理的Python中NotImplementedError的使用方法(抽象类集成子类实现)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。