写一段代码如下:
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()
程序的运行结果如下:
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()