界面

本章包含有关使用的信息 zope.interface 与Pyramid。

动态计算对象提供的接口

(Via Marius Gedminas)

当在pickle或zodb中持久化对象提供的接口对应用程序不合理时,可以使用此技巧动态返回对象基于对象实例中的其他数据提供的接口集:

 1from zope.interface.declarations import Provides
 2
 3from mypackage import interfaces
 4
 5class MyClass(object):
 6
 7    color = None
 8
 9    @property
10    def __provides__(self):
11        # black magic happens here: we claim to provide the right IFrob
12        # subinterface depending on the value of the ``color`` attribute.
13        iface = getattr(interfaces, 'I%sFrob' % self.color.title(),
14                        interfaces.IFrob))
15        return Provides(self.__class__, iface)

如果需要对象实现多个接口,请使用 Provides(self.__class__, iface1, iface2, ...) .