python中的ABC(Abstract Base Class)

一般来讲,抽象类具有的特点有:

  1. 拥有抽象方法,且抽象类不能被实例化
  2. 抽象类的子类必须实现抽象方法后才能被实例化。
    python本身不能支持我们实现一个抽象类,以下语句并无报错。
>>> class Person:
...     def say_something():
...             pass
... 
>>> a = Person()

python用module的方法,提供给我们定义一个抽象类的方式。

from abc import ABC,abstractmethod

class Person(ABC):
    @abstractmethod
    def say_something(self):
        pass

class Student(Person):
    def say_something(self):
        print("i m a student")
    pass

值得注意的是,在抽象类中定义的抽象方法是可以有实现的,不过子类仍需再次实现。

from abc import ABC,abstractmethod

class Person(ABC):
    @abstractmethod
    def say_something(self):
        print("i m a person")

class Student(Person):
    def say_something(self):
        super().say_something()
        print("i m a student")
posted @ 2022-06-11 11:16  somelovelanguage  阅读(246)  评论(0)    收藏  举报