Class factory in Python

后端 未结 7 2361
半阙折子戏
半阙折子戏 2020-11-28 18:37

I\'m new to Python and need some advice implementing the scenario below.

I have two classes for managing domains at two different registrars. Both have the same inte

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 19:12

    I have this problem all the time. If you have the classes embedded in your application (and its modules) then you can use a function; but if you load plugins dynamically, you need something more dynamic -- registering the classes with a factory via metaclasses automatically.

    Here is a pattern I'm sure I lifted from StackOverflow originally, but I don't still have the path to the original post

    _registry = {}
    
    class PluginType(type):
        def __init__(cls, name, bases, attrs):
            _registry[name] = cls
            return super(PluginType, cls).__init__(name, bases, attrs)
    
    class Plugin(object):
        __metaclass__  = PluginType # python <3.0 only 
        def __init__(self, *args):
            pass
    
    def load_class(plugin_name, plugin_dir):
        plugin_file = plugin_name + ".py"
        for root, dirs, files in os.walk(plugin_dir) :
            if plugin_file in (s for s in files if s.endswith('.py')) :
                fp, pathname, description = imp.find_module(plugin_name, [root])
                try:
                    mod = imp.load_module(plugin_name, fp, pathname, description)
                finally:
                    if fp:
                        fp.close()
        return
    
    def get_class(plugin_name) :
        t = None
        if plugin_name in _registry:
            t = _registry[plugin_name]
        return t
    
    def get_instance(plugin_name, *args):
        return get_class(plugin_name)(*args)
    

提交回复
热议问题