Python的抽象类,就是假设我们在一个类Animal中继承ABC类,并且在这个类中定义一个绑定abstractmethod装饰器的方法eat().
如果这个时候再定义一个类Dog继承Animal类,那么Dog类必须得用有eat()方法才不会报错.
话不多说,上代码.
Dog类中有eat()方法
1 from abc import ABC, abstractmethod 2 3 4 class Animal(ABC): 5 @abstractmethod 6 def eat(self): 7 pass 8 9 10 class Dog(Animal): 11 def eat(self): 12 pass 13 14 15 Dog() 16 17 # 输出 18 ''' 19 20 '''
Dog类汇总没有eat()方法
1 from abc import ABC, abstractmethod 2 3 4 class Animal(ABC): 5 @abstractmethod 6 def eat(self): 7 pass 8 9 10 class Dog(Animal): 11 pass 12 13 14 Dog() 15 16 # 输出 17 ''' 18 Traceback (most recent call last): 19 File "C:/test.py", line 14, in <module> 20 Dog() 21 TypeError: Can't instantiate abstract class Dog with abstract methods eat 22 '''