我经常发现自己在编写命令行实用程序,其中第一个参数旨在引用许多不同类中的一个。例如./something.py feature command —-arguments
,where Feature
是一个类,并且command
是该类上的一个方法。这是一个使这变得容易的基类。
假设该基类与所有子类都位于一个目录中。然后ArgBaseClass(foo = bar).load_subclasses()
,您可以拨打电话,这将返回字典。例如,如果目录如下所示:
- arg_base_class.py
- feature.py
假设feature.py
工具class Feature(ArgBaseClass)
,则上述调用load_subclasses
将返回{ 'feature' : <Feature object> }
。相同的kwargs
(foo = bar
)将传递给Feature
该类。
#!/usr/bin/env python3
import os, pkgutil, importlib, inspect
class ArgBaseClass():
# Assign all keyword arguments as properties on self, and keep the kwargs for later.
def __init__(self, **kwargs):
self._kwargs = kwargs
for (k, v) in kwargs.items():
setattr(self, k, v)
ms = inspect.getmembers(self, predicate=inspect.ismethod)
self.methods = dict([(n, m) for (n, m) in ms if not n.startswith('_')])
# Add the names of the methods to a parser object.
def _parse_arguments(self, parser):
parser.add_argument('method', choices=list(self.methods))
return parser
# Instantiate one of each of the subclasses of this class.
def load_subclasses(self):
module_dir = os.path.dirname(__file__)
module_name = os.path.basename(os.path.normpath(module_dir))
parent_class = self.__class__
modules = {}
# Load all the modules it the package:
for (module_loader, name, ispkg) in pkgutil.iter_modules([module_dir]):
modules[name] = importlib.import_module('.' + name, module_name)
# Instantiate one of each class, passing the keyword arguments.
ret = {}
for cls in parent_class.__subclasses__():
path = cls.__module__.split('.')
ret[path[-1]] = cls(**self._kwargs)
return ret