Python 抽象类
1.什么是抽象类
与java一样,python也有抽象类的概念但是同样需要借助模块实现,抽象类是一个特殊的类,它的特殊之处在于只能被继承,不能被实例化
2.为什么要有抽象类
如果说类是从一堆对象中抽取相同的内容而来的,那么抽象类就是从一堆类中抽取相同的内容而来的,内容包括数据属性和函数属性。
比如我们有香蕉的类,有苹果的类,有桃子的类,从这些类抽取相同的内容就是水果这个抽象的类,你吃水果时,要么是吃一个具体的香蕉,要么是吃一个具体的桃子。。。。。。你永远无法吃到一个叫做水果的东西。
从设计角度去看,如果类是从现实对象抽象而来的,那么抽象类就是基于类抽象而来的。
3.在python中实现抽象类
#_*_coding:utf-8_*_
#一切皆文件
importabc#利用abc模块实现抽象类
classAll_file(metaclass=abc.ABCMeta):
all_type='file'
@abc.abstractmethod#定义抽象方法,无需实现功能
defread(self):
'子类必须定义读功能'
pass
@abc.abstractmethod#定义抽象方法,无需实现功能
defwrite(self):
'子类必须定义写功能'
pass
#classTxt(All_file):
#pass
#
#t1=Txt()#报错,子类没有定义抽象方法
classTxt(All_file):#子类继承抽象类,但是必须定义read和write方法
defread(self):
print('文本数据的读取方法')
defwrite(self):
print('文本数据的读取方法')
classSata(All_file):#子类继承抽象类,但是必须定义read和write方法
defread(self):
print('硬盘数据的读取方法')
defwrite(self):
print('硬盘数据的读取方法')
classProcess(All_file):#子类继承抽象类,但是必须定义read和write方法
defread(self):
print('进程数据的读取方法')
defwrite(self):
print('进程数据的读取方法')
wenbenwenjian=Txt()
yingpanwenjian=Sata()
jinchengwenjian=Process()
#这样大家都是被归一化了,也就是一切皆文件的思想
wenbenwenjian.read()
yingpanwenjian.write()
jinchengwenjian.read()
print(wenbenwenjian.all_type)
print(yingpanwenjian.all_type)
print(jinchengwenjian.all_type)
4.抽象类与接口
抽象类的本质还是类,指的是一组类的相似性,包括数据属性(如all_type)和函数属性(如read,write),而接口只强调函数属性的相似性
抽象类是一个介于类和接口直接的一个概念,同时具备类和接口的部分特性,可以用来实现归一化设计
以上内容为大家介绍了Python抽象类,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

猜你喜欢LIKE
相关推荐HOT
更多>>
python中的filter函数功能是什么?
python中的filter函数功能是什么?在python中,面对众多的数据,我们要过滤筛选出我们需要的数据。python中的filter函数就是起到了过滤筛选的作...详情>>
2023-11-10 20:37:27
pythontime模块是什么
pythontime模块是什么在python中使用时间,就免不了和time模块打交道,另外两个模块这个暂时先不做介绍。做time模块的使用上,我们可以用它来对...详情>>
2023-11-10 15:53:16
python是什么编程语言
python是什么编程语言1、说明是一种面向对象、解释型计算机程序设计语言,由GuidovanRossum于1989年底发明,第一个公开发行版发行于1991年。Pyt...详情>>
2023-11-10 15:21:05
python异常处理的两种技巧
python异常处理的两种技巧1、传递异常有时我们会在捕捉到一个异常后重新引发它(传递异常),实现起来很简单,使用不带参数的raise语句即可。deff...详情>>
2023-11-10 14:49:39热门推荐
python中的filter函数功能是什么?
沸python delattr函数如何使用?
热python中pdb模块怎么用?
热Python如何截图保存?
新python中缺少module怎么办?
python strftime和strptime的不同分析
python time.strptime的格式化
python中@contextmanager是什么?
python对象的三要素是什么
pythonGIL在Python多线程的应用
python如何对多个CSV文件进行读取
pythonif嵌套命令如何理解?
python对列表进行永久性或临时排序的方法
python生成器调用方法引发异常
技术干货






