首页 > 其他 > 详细

构造dict类添加model list

时间:2021-06-04 22:51:32      阅读:30      评论:0      收藏:0      [点我收藏+]

 笔者再看DSSD的过程中,发现原来dict还可以这样扩展,特此记录一下。

单纯的摘选涉及到dict扩展的内容:

def _register_generic(module_dict, module_name, module):
    assert module_name not in module_dict
    module_dict[module_name] = module


class Registry(dict):
    """
    A helper class for managing registering modules, it extends a dictionary
    and provides a register functions.
    Eg. creating a registry:
        some_registry = Registry({"default": default_module})
    There‘re two ways of registering new modules:
    1): normal way is just calling register function:
        def foo():
            ...
        some_registry.register("foo_module", foo)
    2): used as decorator when declaring the module:
        @some_registry.register("foo_module")
        @some_registry.register("foo_module_nickname")
        def foo():
            ...
    Access of module is just like using a dictionary, eg:
        f = some_registry["foo_module"]
    """

    def __init__(self, *args, **kwargs):
        super(Registry, self).__init__(*args, **kwargs)

    def register(self, module_name, module=None):
        # used as function call
        if module is not None:
            _register_generic(self, module_name, module)
            return

        # used as decorator
        def register_fn(fn):
            _register_generic(self, module_name, fn)
            return fn

        return register_fn

  其实fn代表添加的model list,这里我才用添加匿名函数作为示例:

# Eg. creating a registry:
some_registry = Registry({"default": lambda x:x*2})
print(some_registry)
some_registry.register("foo_module", lambda x:x*3)
print(some_registry)
@some_registry.register("foo_module_nickname")
def foo(x):
    return x*4

print(some_registry)
print(some_registry["default"](3))

技术分享图片

构造dict类添加model list

原文:https://www.cnblogs.com/a-runner/p/14851198.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!