看一下注册机制是如何使用的:
registry_machine = Registry('registry_machine')
registry_machine.register()
def print_hello_world(word):
print('hello {}'.format(word))
registry_machine.register()
def print_hi_world(word):
print('hi {}'.format(word))
if __name__ == '__main__':
cfg1 = 'print_hello_word'
registry_machine.get(cfg1)('world')
cfg2 = 'print_hi_word'
registry_machine.get(cfg2)('world')
可以看到,如果创建了一个Registry的对象,并在方法/类定义的时候用装饰器装饰它,则可以通过 registry_machine.get(方法名)的 办法来间接的调用被注册的函数
具体实现细节,注册类的代码
class Registry(object):
def __init__(self, name):
"""
Args:
name (str): the name of this registry
"""
self._name = name
self._obj_map = {}
def _do_register(self, name, obj):
assert (
name not in self._obj_map
), "An object named '{}' was already registered in '{}' registry!".format(name, self._name)
self._obj_map[name] = obj
def register(self, obj=None):
"""
Register the given object under the the name `obj.__name__`.
Can be used as either a decorator or not. See docstring of this class for usage.
"""
if obj is None:
# used as a decorator
def deco(func_or_class):
name = func_or_class.__name__
self._do_register(name, func_or_class)
return func_or_class
return deco
# used as a function call
name = obj.__name__
self._do_register(name, obj)
def get(self, name):
ret = self._obj_map.get(name)
if ret is None:
raise KeyError("No object named '{}' found in '{}' registry!".format(name, self._name))
return ret
registry_machine = Registry('registry_machine')
registry_machine.register()
def print_hello_world(word):
print('hello {}'.format(word))
registry_machine.register()
def print_hi_world(word):
print('hi {}'.format(word))
if __name__ == '__main__':
cfg1 = 'print_hello_word'
registry_machine.get(cfg1)('world')
cfg2 = 'print_hi_word'
registry_machine.get(cfg2)('world')