抽象类
- 抽取多个类相似的部分
- 通过抽象类把子类的规范定义好了,把所有方法都规范起来,降低使用者的使用复杂度
- 本质依然是类,依然可以被继承
- 抽象类只能被继承,不能被实例化
-
1 import abc #利用abc模块实现抽象类 2 class Allflie(metaclass=abc.ABCMeta): 3 all_type = 'file' 4 @abc.abstractmethod #定义抽象方法,无需实现功能 5 def read(self): #规定子类必须定义读功能 6 pass 7 @abc.abstractmethod 8 def write(self):#规定子类必须定义写功能 9 pass 10 # class Txt(Allflie): 11 # pass 12 # t1 = Txt() #报错,子类没有定义抽象方法 13 class Txt(Allflie):#子类继承抽象类,但是必须定义read和write方法 14 def read(self): 15 print('文本数据的读取方法') 16 def write(self): 17 print('文本数据的读取方法') 18 pass 19 class Sata(Allflie): #子类继承抽象类,但是必须定义read和write方法 20 def read(self): 21 print('硬盘数据的读取方法') 22 def write(self): 23 print('硬盘数据的读取方法') 24 25 class Process(Allflie): #子类继承抽象类,但是必须定义read和write方法 26 def read(self): 27 print('进程数据的读取方法') 28 def write(self): 29 print('进程数据的读取方法') 30 31 wenbenwenjian=Txt() 32 yingpanwenjian=Sata() 33 jinchengwenjian=Process() 34 #这样大家都是被归一化了,也就是一切皆文件的思想 35 wenbenwenjian.read()#文本数据的读取方法 36 yingpanwenjian.write()#硬盘数据的读取方法 37 jinchengwenjian.read()#进程数据的读取方法 38 39 print(wenbenwenjian.all_type)#file 40 print(yingpanwenjian.all_type)#file 41 print(jinchengwenjian.all_type)#file