【问题标题】:Can I adapt strings and built-in types in Z我可以在 Z 中调整字符串和内置类型吗
【发布时间】:2026-02-13 23:25:03
【问题描述】:

我有一个类似的界面:

class IRepository(Interface):
    def __init__(path, **options):
        pass

我为 Git 和 Mercurial 实现了这个接口。现在我想编写存储库工厂,它接受一个字符串(路径)并返回一个 IRepository,通过探测它是 git 还是 hg 存储库。

但是,简单地说:

registerAdapter(repofactory, (str, unicode, ), IRepository)

不起作用,因为strunicode 都不支持IInterface 接口。

现在,我要:

registerAdapter(repofactory, (Interface, ), IRepository)

但我想知道是否有接口只匹配字符串对象和其他 Python 内置类型。

【问题讨论】:

    标签: adapter zope zope.interface


    【解决方案1】:

    不,字符串和 unicode 对象不能有接口。但是对于这个用例,我会注册命名实用程序并按名称查找实用程序,或者列出所有可用的实用程序:

    from zope.component import getUtilitiesFor, getUtility
    
    names = [name for name, utility in getUtilitiesFor(IRepository)]
    
    gitrepo = getUtility(IRepository, name='git')
    

    【讨论】:

    • 不完全是一个解决方案,因为字符串是 fs 中的路径,我希望有一个可以探测的适配器。
    最近更新 更多