【问题标题】:Declaring class methods in Zope interfaces在 Zope 接口中声明类方法
【发布时间】:2014-02-02 08:14:36
【问题描述】:

考虑如下类:

from zope.interface import implementer

@implementer(IMessage)
class Foo:

  @classmethod
  def parse(Klass, msg):
  """
  Parses `msg` into an instance of :class:`Foo`.

  :returns obj -- An instance of :class:`Foo`.
  """

如何在 Zope 接口IMessage 中指定类方法?

在 Zope 界面中使用 @classmethod 装饰器会导致

zope.interface.exceptions.InvalidInterface: Concrete attribute, parse

【问题讨论】:

    标签: python interface zope


    【解决方案1】:

    Zope 接口不关心类方法;它们只指定特定接口必须实现的 API。请注意,您指定的方法没有 self 参数,例如。这样,您可以以任何您喜欢的方式实现接口,包括在模块中使用常规函数!

    如果实现选择使该可调用 classmethod 完全超出接口的范围。接口只关心你在访问接口提供者时使用什么 API;如果一个实例有一个可调用对象,那么最终用户不需要关心它是否是一个类方法。

    如果类方法应该直接在类上可用,那么这就是必须提供的接口;让我们在这里将其称为工厂接口:

    class IMessageFactory(Interface):
         def __call__():
             """Produce an IMessage provider"""
    
         def parse(msg):
             """Parses `msg` into a IMessage provider"""
    
    
    class IMessage(Interface):
         """A message interface"""
    
         # Optional, show the class method here too
         def parse(msg):
             """Parses `msg` into a IFoo provider"""
    

    您的Foo 类直接提供IMessageFactory,并实现IMessage 接口(以便它的实例提供它)。

    【讨论】:

    • 谢谢!工厂接口和实例接口的区别是有道理的,并且非常清楚地暴露了意图。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 2014-05-09
    • 1970-01-01
    相关资源
    最近更新 更多