程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

接口类

发布于2020-03-19 11:21     阅读(3937)     评论(0)     点赞(4)     收藏(5)


引言:
在我们日常生活中用电脑存储数据时,会用到磁盘存储 文件存储 存储器存储等,每种存储方式都会有读数据和写数据两种操作,那么读和写操作可以提出来单写成一个类。剩下三个类去继承他的方法即可。但是要注意:我们需要这三种方法必须都有读写两种方法,这时就需要用到接口类。
例:
首先演示一个没有用到接口类的,在Mem类中只实现了read()方法,程序可执行

class All_file():
    def read(self):
        pass
    def write(self):
        pass
class Txt(All_file):
    def read(self):
        print('文本数据的读取方法')
    def write(self):
        print('文本数据的写方法')
class Disk(All_file):
    def read(self):
        print('磁盘数据的读取方法')

class Mem(All_file):
    def read(self):
        print('mem read')
m1=Mem()
m1.read()

结果
mem read
使用接口类后:

import abc
class All_file(metaclass=abc.ABCMeta):
    @abc.abstractmethod
    def read(self):
        pass

    @abc.abstractmethod
    def write(self):
        pass
class Txt(All_file):
    def read(self):
        print('文本数据的读取方法')
    def write(self):
        print('文本数据的写方法')
class Disk(All_file):
    def read(self):
        print('磁盘数据的读取方法')

class Mem(All_file):
    def read(self):
        print('mem read')

    # def write(self):
    #     print('mem write')
m1=Mem()
m1.read()

结果:

Traceback (most recent call last):
  File "E:/python_workspace/test/le/bin.py", line 41, in <module>
    m1=Mem()
TypeError: Can't instantiate abstract class Mem with abstract methods write

这就实现了父类对它子类的一个限制,限制子类必须有读和写两种方法。而且接口类中的方法不必实现,她就是起到一个限制作用的。



所属网站分类: 技术文章 > 博客

作者:编程gogogo

链接:https://www.pythonheidong.com/blog/article/268433/b938f17dbd75733a035c/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

4 0
收藏该文
已收藏

评论内容:(最多支持255个字符)