我想让"C++强制转换类似“适应与来自zope.interface的代码一起工作。在我的实际用例中,我使用的是来自Pyramid的注册表,但它来自于zope.interface.registry.Components,根据changes.txt的说法,zope.interface.registry.Components是为了能够在不依赖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:(“无法适应”,<. 0x4d1c3d0>中的一个对象,< InterfaceClass ....IB>)
知道该怎么做吗?
发布于 2014-07-16 21:58:17
要使IB(A())工作,您需要向zope.interface.adapter_hooks列表中添加一个钩子;IAdapterRegistry接口有一个专用的IAdapterRegistry.adapter_hook方法,我们可以用于这个方法:
from zope.interface.interface import adapter_hooks
adapter_hooks.append(registry.adapters.adapter_hook)参见适应中的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'>https://stackoverflow.com/questions/24791239
复制相似问题