Skip to main content
 首页 » 编程设计

python之如何让 "cast like"适应纯 zope.interface

2024年10月25日10傻小

我想获得“C++ cast like”适配以使用来自 zope.interface 的代码。在我的实际用例中,我使用的是 Pyramid 中的注册表,但它派生自 zope.interface.registry.Components,根据 changes.txt,它被引入到能够在不依赖于 zope.components 的情况下使用这些东西。以下示例是完整且自包含的:

from zope.interface import Interface, implements                                  
from zope.interface.registry import Components   
 
registry = Components()                                                           
 
class IA(Interface):                                                              
    pass                                                                          
 
class IB(Interface):                                                              
    pass                                                                          
 
class A(object):                                                                  
    implements(IA)                                                                
 
class B(object):                                                                  
    implements(IB)                                                                
    def __init__(self,other):                                                     
        pass                                                                      
 
registry.registerAdapter(                                                         
    factory=B,                                                                    
    required=[IA]                                                                 
)                                                                                 
 
a = A()                                                                           
b = registry.getAdapter(a,IB) # why instance of B and not B?                                                  
b = IB(A()) # how to make it work? 

我想知道为什么 registry.getAdapter 已经返回了适配对象,在我的例子中它是 B 的一个实例。我本希望返回 B 类,但也许我对术语适配器的理解是错误的。由于这一行有效并且显然适配代码已正确注册,因此我也希望最后一行有效。但它失败并出现如下错误:

TypeError: ('Could not adapt', <....A object at 0x4d1c3d0>, < InterfaceClass ....IB>)

知道如何让它工作吗?

请您参考如下方法:

要使 IB(A()) 工作,您需要在 zope.interface.adapter_hooks 列表中添加一个钩子(Hook); IAdapterRegistry 接口(interface)有一个专用的 IAdapterRegistry.adapter_hook 方法,我们可以为此使用:

from zope.interface.interface import adapter_hooks 
 
adapter_hooks.append(registry.adapters.adapter_hook) 

参见 Adaptation在 zope.interface 自述文件中。

您可以使用 IAdapterRegistry.lookup1()在不调用工厂的情况下进行单适配器查找的方法:

from zope.interface import providedBy 
 
adapter_factory = registry.adapters.lookup1(providedBy(a), IB) 

以您的示例为基础:

>>> from zope.interface.interface import adapter_hooks 
>>> adapter_hooks.append(registry.adapters.adapter_hook) 
>>> a = A() 
>>> IB(a) 
<__main__.B object at 0x100721110> 
>>> from zope.interface import providedBy 
>>> registry.adapters.lookup1(providedBy(a), IB) 
<class '__main__.B'>