面向接口编程

目录


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 却没有实现接口的话,直接调用就会报错。



更多文章
  • Git HTTPS 如何保存密码
  • 程序员修炼之道 阅读笔记
  • Python开发实践经验
  • Golang实现平滑重启(优雅重启)
  • traefik 教程
  • Web开发系列(十):事务和锁
  • Web开发系列(十一):数据库扩展
  • Nginx作为TCP/UDP的负载均衡
  • Web开发简介系列
  • Web开发系列(九):消息队列,异步任务
  • Nginx 请求匹配规则
  • Web开发系列(六):关系型数据库,ORM
  • Web开发系列(七):缓存,CDN
  • Web开发系列(八):单点故障,负载均衡
  • Web开发系列(五):form, json, xml