Skip to main content
 首页 » 编程设计

python之尝试注册 zope.interface 的实现者时出错

2024年10月01日6myhome

我有下一节课:

@implementer(ISocial) 
class SocialVKSelenium: 
    pass 

当我将它添加到 zope 注册表时:

gsm = getGlobalSiteManager() 
gsm.registerAdapter(SocialVKSelenium) 

我得到:TypeError:适配器工厂没有 __component_adapts__ 属性,也没有指定必需的规范

当我在其中添加适配器 (IOther) 时,注册会按预期工作,但没有则不会。为什么会这样?

请您参考如下方法:

您需要在类上或注册表中提供上下文。

我怀疑您没有传达您的问题集的全部 - 适配器是一个组件,它适配一个指定接口(interface)的对象,并提供另一个。您的示例未能指定要适配的上下文是什么,也就是说,在您的适配器对象的类构造中适配了哪种对象?

例如,这工作正常:

from zope.interface import Interface, implements 
from zope.component import getGlobalSiteManager, adapts 
 
 
class IWeight(Interface): 
    pass 
 
 
class IVolume(Interface): 
    pass 
 
class WeightToVolume(object): 
    implements(IVolume) 
    adapts(IWeight) 
    #... 
 
 
gsm = getGlobalSiteManager() 
gsm.registerAdapter(WeightToVolume) 

虽然您可以为此使用装饰器(实现器/适配器)语法,但按照惯例,对于作为类而不是函数的适配器工厂,首选使用实现/适配器。

如果您的适配器没有在类或工厂函数本身上声明它所适应的内容,您至少需要告知注册表。在最广泛的情况下,这可能看起来像:

gsm.registerAdapter(MyAdapterClassHere, required=(Interface,)) 

当然,上面的这个例子是一个适配器,它声称可以适应任何上下文,除非您知道为什么需要它,否则不推荐这样做。