开发者

Creating an interface and swappable implementations in python

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

Example: I want to create a class for pop3 access (and all methods etc.). If I go with a commercial component, I want t开发者_如何学JAVAo 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.

Possible? I'm new to 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):
    ...

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.

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


Of course. There is no need to create a base class or an interface in this case either, as everything is dynamic.


One option is to use zope interfaces. However, as was stated by Wai Yip Tung, you do not need to use interfaces to achieve the same results.

The zope.interface package is really more a tool for discovering how to interact with objects (generally within large code bases with multiple developers).


Yes, this is possible. There are typically no impediments to doing so: just keep a stable API and change how you implement it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜