简体   繁体   English

Zope 接口继承:为什么它不显示在 interface.providedBy() 中?

[英]Zope interface inheritance: Why doesn't it show up in interface.providedBy()?

I would expect when I make an interface IB inherit from IA , then use interface.providedBy() to query an instance of B (which implements IB ), I would see both IA and IB in the list.我希望当我让接口IBIA继承,然后使用interface.providedBy()查询B的实例(实现IB )时,我会在列表中看到IAIB However, that doesn't seem to be the case.然而,情况似乎并非如此。

from zope import interface

class IA(interface.Interface):
    pass

class IB(IA): # We inherit from IA
    pass

class B(object):
    interface.implements(IB)

if __name__ == '__main__':
    b = B()
    print 'Does B() provide IA? %s' % IA.providedBy(b)
    print 'providedBy(B()): %s' % list(interface.providedBy(b))

Running this code produces the following output:运行此代码会产生以下输出:

Does B() provide IA? True
providedBy(B()): [<InterfaceClass __main__.IB>]

If B() provides IA , as shown in the first line of output, why doesn't IA show up in the second line of output?如果B()提供IA ,如第一行输出所示,为什么IA不显示在第二行输出中?

UPDATE: I resolved the issue by using the following workaround.更新:我通过使用以下解决方法解决了该问题。 I had no interest in seeing any of the provider classes, the base class (zope.interface.Interface) or any kind of duplicates in the results, so I did the following.我没有兴趣在结果中看到任何提供程序类、基类 (zope.interface.Interface) 或任何类型的重复项,因此我执行了以下操作。

def getAllInterfaces(obj):
    all_ifaces = set()

    def buildSet(ifaces):
        for iface in ifaces:
            if iface != interface.Interface:
                all_ifaces.add(iface)
                buildSet(iface.__bases__)

    buildSet(list(interface.providedBy(obj)))
    return tuple(all_ifaces)

providedBy only returns immediately provided interfaces. providedBy 只返回立即提供的接口。 See https://github.com/Pylons/substanced/blob/master/substanced/util/ init .py#L398 for an example of how to obtain all the interfaces.https://github.com/Pylons/substanced/blob/master/substanced/util/初始化的.py#L398为如何获取所有接口的例子。

The short form to get all the provided interfaces is this:获取所有提供的接口的简短形式是这样的:

from zope.interface.declarations import Declaration
from zope.interface import providedBy

allProvidedInterfaces = list(Declaration(providedBy(b)).flattened())

It is based on the hint of @chris-mcdonough and on this method: https://github.com/Pylons/substanced/blob/a897f4a0518c51b6e093cc5af39fa326f23752c2/substanced/util/ init .py#L426它是基于@克里斯-麦克唐纳的暗示,这种方法: https://github.com/Pylons/substanced/blob/a897f4a0518c51b6e093cc5af39fa326f23752c2/substanced/util/初始化的.py#L426

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM