面向接口编程

目录


Python中没有对接口的直接支持,但是实际上面向接口编程是一种编程思维、编程范式,与语言是否有关键字支持无关。Python中面向 接口编程我们一般使用 abc

In [1]: import abc

In [2]: class Bird(abc.ABC):
   ...:     @abc.abstractmethod
   ...:     def fly(self):
   ...:         pass
   ...:

In [3]: class Parrot(Bird):
   ...:     pass
   ...:

In [4]: Parrot().fly()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-4-beb5d307db79> in <module>
----> 1 Parrot().fly()

TypeError: Can't instantiate abstract class Parrot with abstract methods fly

In [5]: class Parrot(Bird):
   ...:     def fly(self):
   ...:         print("flying")
   ...:

In [6]: Parrot().fly()
flying

可以看到,如果我们继承了 Bird 却没有实现接口的话,直接调用就会报错。



更多文章
  • Go设计模式:模板模式
  • Go设计模式:适配器模式
  • Go设计模式:Iterator
  • glusterfs 笔记
  • 用peewee代替SQLAlchemy
  • Go的slice工作机制
  • Linux系统迁移记录(从HDD到SSD)
  • Redis是如何工作的?
  • virsh自动关闭windows虚拟机
  • Golang sort源码阅读
  • 分治的思维方式
  • Debian 使用NetworkManager之后networking.service崩溃
  • httprouter源码阅读与分析
  • 《程序员的自我修养-装载、链接与库》笔记
  • Golang sync.Pool源码阅读与分析