编程语言
首页 > 编程语言> > python中的ABC(Abstract Base Class)

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")

标签:ABC,python,Abstract,Person,say,Base,something,抽象类,class
来源: https://www.cnblogs.com/pitaya01/p/16365503.html