在python中创建接口和可交换实现 [英] Creating an interface and swappable implementations in python

查看:78
本文介绍了在python中创建接口和可交换实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能在python中创建一个类接口以及该接口的各种实现.

Would it be possible to create a class interface in python and various implementations of the interface.

示例:我想创建一个用于pop3访问的类(以及所有方法等).如果我使用商业组件,则希望将其包装以遵守合同.

Example: I want to create a class for pop3 access (and all methods etc.). If I go with a commercial component, I want to wrap it to adhere to a contract.

将来,如果我想使用其他组件或编写自己的代码,我希望能够交换内容,而又不让它们紧密耦合.

In the future, if I want to use another component or code my own, I want to be able to swap things out and not have things very tightly coupled.

可能吗?我是python的新手.

Possible? I'm new to python.

推荐答案

对于来自强类型语言背景的人们,Python不需要类接口.您可以使用基类对其进行仿真.

For people coming from a strongly typed language background, Python does not need a class interface. You can simulate it using a base class.

class BaseAccess:
  def open(arg):
    raise NotImplementedError()

class Pop3Access(BaseAccess):
  def open(arg):
    ...

class AlternateAccess(BaseAccess):
  def open(arg):
    ...

但是您无需使用BaseAccess即可轻松编写相同的代码.强类型语言需要在编译时进行类型检查的接口.对于Python,这不是必需的,因为在运行时会动态查找所有内容. Google'鸭子打字'为其哲学.

But you can easily write the same code without using BaseAccess. Strongly typed language needs the interface for type checking during compile time. For Python, this is not necessary because everything is looked up dynamically in run time. Google 'duck typing' for its philosophy.

Python 2.6中添加了一个抽象基类模块.但是我还没有用过.

There is a Abstract Base Classes module added in Python 2.6. But I haven't have used it.

这篇关于在python中创建接口和可交换实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆