zope.interface 库学习一

时间:2021-03-25 20:58:50

由于python没有接口概念,所以zope 提供了个第三方库开源使用,下面简单介绍zope.interface.implementer的使用

直接看例子,下面例子是在twisted里摘录的

接口IResolverSimple

class IResolverSimple(Interface):
    def getHostByName(name, timeout = (1, 3, 11, 45)):
        """
        Resolve the domain name C{name} into an IP address.
        """

实现BlockingResolver

@implementer(IResolverSimple)
class BlockingResolver:

    def getHostByName(self, name, timeout = (1, 3, 11, 45)):
        try:
            address = socket.gethostbyname(name)
        except socket.error:
            msg = "address %r not found" % (name,)
            err = error.DNSLookupError(msg)
            return defer.fail(err)
        else:
            return defer.succeed(address)

可以通过

IResolverSimple.implementedBy

IResolverSimple.providedBy

对实现进行检测

foo = BlockingResolver()

IResolverSimple.implementedBy(BlockingResolver) #display True

IResolverSimple.implementedBy(foo) #display True