【python 9】python注册器
生活随笔
收集整理的這篇文章主要介紹了
【python 9】python注册器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 一、什么是 python 注冊器
- 二、python 注冊器怎么用
一、什么是 python 注冊器
python 的 register 類可以理解為一個字典,這個字典里邊會存儲很多相同系列的類。
注冊器也可以讓工程擴展性變好,當需要增加新類的時候,可以復用之前的邏輯,只需要給注冊器這個字典里邊添加即可。
二、python 注冊器怎么用
以 mmdet 為例,mmdet/models/registry.py 代碼如下:
# mmdet.utils 的 Registry 中實現了注冊器類 from mmdet.utils import Registry # 這里都是對注冊器類的實例化,傳入的是一個字符串,這個字符串是name屬性 # 注冊了一個對象名為 BACKBONES,屬性名為 backbone 的對象 BACKBONES = Registry('backbone') NECKS = Registry('neck') ROI_EXTRACTORS = Registry('roi_extractor') SHARED_HEADS = Registry('shared_head') HEADS = Registry('head') LOSSES = Registry('loss') DETECTORS = Registry('detector')簡單例子:
class RegisterMachine(object):def __init__(self, name):# name of registerself._name = nameself._name_method_map = dict()def register(self, obj=None):# obj == None for function call register# otherwise for decorator wayif obj != None:name = obj.__name__self._name_method_map[name] = objelse:def wrapper(func):name = func.__name__self._name_method_map[name] = funcreturn funcreturn wrapperdef get(self, name):return self._name_method_map[name]if __name__ == "__main__":register_obj = RegisterMachine("register") # <__main__.RegisterMachine object at 0x7fa5d8aaba00># register_obj._name = 'register'# register_obj._name_method_map = {}# decorate method@register_obj.register()def say_hello_with(name):print("Hello, {person}!".format(person=name))def say_hi_with(name):print("Hi, {person}!".format(person=name))register_obj.get("say_hello_with")("Peter") # output: Hello, Peter!# 這個時候的 register_obj: # {# 'say_hello_with': <function say_hello_with at 0x7feb6ca2e790># }register_obj.register(say_hi_with) # output: None# 這個時候的 register_obj: # {# 'say_hello_with': <function say_hello_with at 0x7feb6ca2e790>, # 'say_hi_with': <function say_hi_with at 0x7feb6dc821f0># }register_obj.get("say_hi_with")("John") # output: Hi, John!# 這個時候的 register_obj: # {# 'say_hello_with': <function say_hello_with at 0x7feb6ca2e790>, # 'say_hi_with': <function say_hi_with at 0x7f7c91ce41f0># } register_obj.get("say_hello_with")("Peter") # get → register → say_hello_with register_obj.get("say_hi_with")("John") # get → say_hi_with總結
以上是生活随笔為你收集整理的【python 9】python注册器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【python 8】python 装饰器
- 下一篇: 【python 10】python 魔术