无名阁,只为技术而生。流水不争先,争的是滔滔不绝。

Python编程中NotImplementedError的使用方法 特殊异常NotImplementedError:标记抽象方法 全网首发(图文详解1)

前沿技术 Micheal 4个月前 (05-19) 43次浏览 已收录 扫描二维码

Python编程中NotImplementedError的使用方法

在Python编程中,NotImplementedError是一种特殊的异常,通常用于标记抽象方法,即尚未实现的方法,但在未来的子类中可能会被覆盖或实现。当你设计一个有基类或抽象类的面向对象结构时,如果某些方法应由子类实现,那么在基类里可以通过抛出NotImplementedError来达到这个目的。当试图直接调用该抽象方法时,会抛出NotImplementedError异常。

使用NotImplementedError的一般步骤如下:

  • 在基类或抽象类中定义一个或多个方法。
  • 在这些方法中通过raise NotImplementedError()来抛出 NotImplementedError异常。
  • 创建子类并重写这些方法,实现具体的功能。

下面是一个具体的示例:

class Animal:
    def sound(self):
        raise NotImplementedError("子类必须实现此方法")

class Dog(Animal):
    def sound(self):
        return "汪汪"

class Cat(Animal):
    def sound(self):
        return "喵喵"

# 如果直接创建Animal对象并调用sound方法,会触发NotImplementedError
try:
    animal = Animal()
    animal.sound()
except NotImplementedError as e:
    print(e)

# 创建Dog对象并调用sound方法,不会出错,输出"汪汪"
dog = Dog()
print(dog.sound()) 

# 创建Cat对象并调用sound方法,不会出错,输出"喵喵"
cat = Cat()
print(cat.sound())  

在上面这个例子中,Animal是一个基类,它有一个sound的方法。这个方法被设计为要被Dog和Cat这两个子类重写。如果我们直接用Animal类生成对象并尝试调用其sound方法的话,由于Animal类中的sound方法并没有实现具体的内容,而是抛出了NotImplementedError,所以在执行的时候会触发NotImplementedError。但当我们用Dog类和Cat类生成对象并调用它们的sound方法的时候,就不会报错,因为在这两个子类中已经实现了sound方法。
(pandas concat) 详解Pandas concat连接操作的5种使用方法 Pandas.concat函数常用方式 全网首发(图文详解1)
(Python) Python 删除对象方法del()详解 对象销毁机制$__ 全网首发(图文详解1)

喜欢 (0)
[]
分享 (0)
关于作者:
流水不争先,争的是滔滔不绝