鱼C论坛

 找回密码
 立即注册
查看: 1454|回复: 0

[技术交流] 标准库:abc抽象基类

[复制链接]
发表于 2022-3-12 23:39:53 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x

##问题
你想定义一个接口或抽象类,并且通过执行类型检查来确保子类实现了某些特定的方法,类似于Java的接口。

##解决方案
使用 abc 模块可以很轻松的定义抽象基类:
  1. from abc import ABCMeta, abstractmethod

  2. class IStream(metaclass=ABCMeta):
  3.     @abstractmethod
  4.     def read(self, maxbytes=-1):
  5.         pass

  6.     @abstractmethod
  7.     def write(self, data):
  8.         pass
复制代码


抽象类的一个特点是它不能直接被实例化,比如你想像下面这样做是不行的:
  1. >>> from module_abc import IStream
  2. >>> a = IStream()
  3. Traceback (most recent call last):
  4.   File "<stdin>", line 1, in <module>
  5. TypeError: Can't instantiate abstract class IStream with abstract methods read, write
  6. >>>
复制代码


抽象类的目的就是让别的类继承它并实现特定的抽象方法:
  1. from abc import ABCMeta, abstractmethod


  2. class IStream(metaclass=ABCMeta):
  3.     @abstractmethod
  4.     def read(self, maxbytes=-1):
  5.         pass

  6.     @abstractmethod
  7.     def write(self, data):
  8.         pass


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

  10. class SocketStream(IStream):
  11.     def read(self, maxbytes=-1):
  12.         pass

  13.     def write(self, data):
  14.         pass
复制代码




- 参考文章:
  • https://python3-cookbook.readthedocs.io/zh_CN/latest/c08/p12_define_interface_or_abstract_base_class.html
  • https://docs.python.org/zh-cn/3/library/abc.html
  • 本帖被以下淘专辑推荐:

    想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

    GMT+8, 2024-4-20 01:15

    Powered by Discuz! X3.4

    © 2001-2023 Discuz! Team.

    快速回复 返回顶部 返回列表