zoukankan      html  css  js  c++  java
  • Python 定义接口和抽象类

    JAVA由于不支持多继承,故创造了接口这个概念来解决这个问题。而Python本身是支持多继承的,故在Python中,没有接口这种类,只有这个概念而已,只不过Python中的接口实现,是通过多继承实现的。

    解决方案

    使用 abc 模块可以很轻松的定义抽象基类:

    from abc import ABCMeta, abstractmethod
     
    class IStream(metaclass=ABCMeta):
      @abstractmethod
      def read(self, maxbytes=-1):
        pass
     
      @abstractmethod
      def write(self, data):
        pass

    抽象类的一个特点是它不能直接被实例化,比如你想像下面这样做是不行的

    a = IStream() # TypeError: Can't instantiate abstract class
            # IStream with abstract methods read, write

    类继承接口:

    class SocketStream(IStream):
      def read(self, maxbytes=-1):
        pass
     
      def write(self, data):
        pass

    除了继承这种方式外,还可以通过注册方式来让某个类实现抽象基类:

    import io
     
    # Register the built-in I/O classes as supporting our interface
    IStream.register(io.IOBase)
     
    # Open a normal file and type check
    f = open('foo.txt')
    isinstance(f, IStream) # Returns True

  • 相关阅读:
    淘宝返回顶部
    混合布局
    css布局使用定位和margin
    选项卡 js操作
    ul li 好友列表
    js添加删除元素
    下拉列表的简单操作
    python笔记
    kali linux 虚拟机网卡未启动
    python 重新安装pip(python2和python3共存以及pip共存)
  • 原文地址:https://www.cnblogs.com/kpwong/p/14144914.html
Copyright © 2011-2022 走看看