【问题标题】:Why would a subclass of a subclass of zope.interface.Interface not inherit its parents names?为什么 zope.interface.Interface 的子类的子类不会继承其父名称?
【发布时间】:2012-05-30 19:24:55
【问题描述】:

例子:

>>> from zope.interface import Interface, Attribute
>>> class IA(Interface):
...   foo = Attribute("foo")
... 
>>> IA.names()
['foo']
>>> class IB(IA):
...   bar = Attribute("bar")
... 
>>> IB.names()
['bar']

如何让 IB.names() 也返回 IA 中定义的属性?

【问题讨论】:

    标签: python zope.interface


    【解决方案1】:

    如果您查看zope.interface.interfaces module,您会发现Interface 类有一个IInterface interface definition!它记录了names 方法如下:

    def names(all=False):
        """Get the interface attribute names
    
        Return a sequence of the names of the attributes, including
        methods, included in the interface definition.
    
        Normally, only directly defined attributes are included. If
        a true positional or keyword argument is given, then
        attributes defined by base classes will be included.
        """
    

    因此扩展您的示例:

    >>> from zope.interface import Interface, Attribute
    >>> class IA(Interface):
    ...     foo = Attribute("foo")
    ... 
    >>> IA.names()
    ['foo']
    >>> class IB(IA):
    ...     bar = Attribute("bar")
    ... 
    >>> IB.names()
    ['bar']
    >>> IB.names(all=True)
    ['foo', 'bar']
    

    【讨论】:

    • 谢谢。由于某种原因,docs.zope.org 上的 zope.interface 消失了,直到我发布问题后我才想到检查方法签名。
    【解决方案2】:

    知道了:

    IB.names(all=True)
    

    我想我以后应该更多地检查方法签名。

    【讨论】:

      猜你喜欢
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多