抽象基类
作用:抽象基类 定义了接口规范,其子类必须实现抽象基类父类里的抽象方法
abc模块
python使用abc模块定义抽象基类
而abc模块提供三个装饰器
- abc.abstractclassmethod:抽象类方法
- abc.abstractstaticmethod:抽象静态方法
- abc.abstractmethod:抽象实例方法
from abc import ABC,abstractmethod
class Animal(ABC):
#定义抽象方法
@abstractmethod
def eat(self):
print("this is eat")
def drink(self):
pass
class Dog(Animal):
def eat(self):
print('dog is eating')
#d0 = Animal()
d1 = Dog()
在Animal类中定义了抽象方法eat,因此dog类继承自Animal必须重写eat方法,否则会报错,且你无法实例化Animal类。