python支持多继承,但是不支持接口,zope.inteface是其三方的接口实现库,在twisted中有大量使用
from zope.interface import Interface
from zope.interface import implementer
import socket
class IHostNameResolver(Interface):
def getHostByName(name, timeout = (1, 3, 11, 45)): # 可以不用self
"""
Resolve the domain name C{name} into an IP address.
"""
"""
类装饰器等价于:implementer(IHostNameResolver)(HostNameResolver)
"""
@implementer(IHostNameResolver)
class HostNameResolver:
def getHostByName(self, name, timeout = (1, 3, 11, 45)):
try:
address = socket.gethostbyname(name)
except socket.error:
return 'none'
else:
return address
resolver = HostNameResolver()
print resolver.getHostByName('localhost')
# 判断HostNameResolver是否实现了接口IHostNameResolver
print IHostNameResolver.implementedBy(HostNameResolver) # True, 调用 SpecificationBasePy.implementedBy()