您可以使用元类型创建接口的动态子类InterfaceClass
。
创建附加模式字段的字典:
fields = {}
for name, attr in IMember.namesAndDescriptions():
if isinstance(attr, schema.Field):
fields['visible_' + name] = schema.Bool(title=u'Display: ' + attr.title)
现在您可以创建一个动态接口子类化现有接口:
from zope.interface.interface import InterfaceClass
IMemberExtended = InterfaceClass('IMemberExtended', (IMember,), fields)
如果您愿意,这一切都可以包含在类装饰器中:
from zope.interface.interface import InterfaceClass
from zope import schema
def add_visibility_fields(iface):
fields = {}
for name, attr in iface.namesAndDescriptions():
if isinstance(attr, schema.Field):
fields['visible_' + name] = schema.Bool(title=u'Display: ' + attr.title)
return InterfaceClass(iface.__name__, (iface,), fields)
您将在现有界面上使用:
@add_visibility_fields
class IMember(Interface):
first_name = schema.TextLine(title=u'first name')
last_name = schema.TextLine(title=u'last name')
这将创建一个子类;您还可以将整个界面替换为生成的界面:
def add_visibility_fields(iface):
fields = {}
for name, attr in iface.namesAndDescriptions():
fields[name] = attr
if isinstance(attr, schema.Field):
fields['visible_' + name] = schema.Bool(title=u'Display: ' + attr.title)
return InterfaceClass(iface.__name__, iface.__bases__, fields)
最后一个版本的演示:
>>> @add_visibility_fields
... class IMember(Interface):
... first_name = schema.TextLine(title=u'first name')
... last_name = schema.TextLine(title=u'last name')
...
>>> IMember.names()
['visible_last_name', 'first_name', 'last_name', 'visible_first_name']