zoukankan      html  css  js  c++  java
  • python学习-NotImplementedError的使用

    谨以此文,记录自己在学习python过程中遇到的问题和知识点。如有错漏,还请各位朋友指正,感谢!

    问题简述

    在python中,raise可以实现报出错误的功能,而报出错误的条件是程序员可以自己规定的。在面向对象编程中,如果想在父类中预留一个方法,使该方法在子类中实现。如果子类中没有对该方法进行重写就被调用,则报NotImplementError这个错误。

    代码理解

    如下面代码所示,子类Two中没有重写父类One中的show方法,就对其进行了调用:

    class One(object):
        
        def show(self):
            raise NotImplementedError
    
    class Two(One):
        
        def show_of_two(self):
            print('hello world!')
    
    number = Two()
    number.show()
    

    运行上述代码的结果如下:(报出NotImplementedError)

    Traceback (most recent call last):
      File "c:/Users/Sykai/Desktop/PyLearn/test.py", line 20, in <module>
        number.show()
      File "c:/Users/Sykai/Desktop/PyLearn/test.py", line 12, in show
        raise NotImplementedError
    NotImplementedError
    

    正确使用方法应该如下所示:

    class One(object):
        
        def show(self):
            raise NotImplementedError
    
    class Two(One):
        
        def show(self):
            print('hello world!')
    
    number = Two()
    number.show()
    

    运行代码输出结果:

    hello world!
    
  • 相关阅读:
    函数式宏定义与普通函数
    linux之sort用法
    HDU 4390 Number Sequence 容斥原理
    HDU 4407 Sum 容斥原理
    HDU 4059 The Boss on Mars 容斥原理
    UVA12653 Buses
    UVA 12651 Triangles
    UVA 10892
    HDU 4292 Food
    HDU 4288 Coder
  • 原文地址:https://www.cnblogs.com/sykline/p/14630854.html
Copyright © 2011-2022 走看看