In objects interfaces are used as follows:

在对象里接口是这样被使用的:

The implements() method tells the system that instances of the class provide IExample. But of course, modules and classes themselves can implement interfaces as well. For modules you can use moduleProvides(*interfaces). For classes you can insert classImplements(*interfaces) directly in the class definition or use classProvides(cls,*interfaces) for an existing class. Also, you can use directlyProvides(instance,*interfaces) for any object as well (including instances of classes).

implements()方法告诉系统这个类的实例提供IExample。但是当然,模块和类本身也可以实现接口。对于模块来说你可以使用moduleProvides(*interfaces)。对于类来说,你可以直接在类的定义里插入classImplements(*interfaces)或者对现有的类使用classProvides(cls,*interfaces)。同样,你可以使用在任何对象(包括类的实例)上使用directlyProvides(instance,*interfaces)。

The Interface object itself has some nice methods. The most common one is providedBy(ob), which checks whether the passed object implements the interface or not:

接口对象本身含有一些非常棒的方法。最普通的一个就是providedBy(ob),它可以检测传递过来的对象是否是实现了这个接口。

Similarly you can pass in a class and test whether instances of this class implement the interface by calling IExample.implementedBy(SimpleExample). The last useful method is isOrExtends(interface). This method checks whether the passed interface equals the interface or whether the passed interface is a base (extends) of the interface.

同样的,你也可以通过调用IExample.implementedBy(SimpleExample)来传递到类里面并测试这个类的实例是否实现了这个接口。最后一个有用的方法是isOrExtends(interface)。这个方法用来检测传递的接口是否是接口或者传递的接口是否是这个接口的基(继承)接口。

When creating classes from an interface, there is a helpful script called pyskel.py that creates a class skeleton from an interface. Before using the script you have to make sure the ZOPE3/src is in your Python path.

Usage: python2.3 utilities/pyskel.py dotted.path.ref.to.interface

当从接口创建类的时候,有一个很有帮助性的脚本叫pyskel.p,它可以帮助你生成类的骨架。在使用这个脚本之前,请确保ZOPE3/src在你的Python路径中。

使用方法:python2.3 utilities/pyskel.py dotted.path.ref.to.interface

This call creates a skeleton of the class in your console, which saves you a lot of typing. The order of the attributes and methods as they appear in the interface is preserved.

这个调用将在你的控制台里创建类的骨架,它可以帮助你省去大量的输入。属性和方法的顺序与在接口里面出现的顺序是一样的。

As a last note, since Python does not comone with interfaces, the zope. interface package provides some interfaces that are implemented by the built-in Python types. They can be found in zope.interface.common.

最后需要注意的是,由于Python没有提供接口,那么zope. Interface包提供的一些实现了Python内建类型的接口。你可以在zope.interface.common里找到它们。

This concludes the overview of interfaces. This introduction should be sufficient to get you started with the chapters. Many of the concepts will become much clearer as you work through the hands-on examples of the following parts of the book.

这就是接口的概览。这些介绍应该足够你开始下面章节的学习了。更多的概念将在你学习和使用本书余下部分的过程中变得愈加清晰起来。