当父类和子类都在一个文件下时,直接在父类中调用 __subclassess__就可以获得所有子类,如:
class A(object): pass class B(A): pass class C(A): pass for sub in A.__subclasses__(): print(sub.__name__)
但是当子类和父类不在一个文件下时就会获取不到, 就需要通过动态导包来实现,我这里是父类和子类在同一个目录下,如果目录不同,则自己调整路径就行,代码参考:
class A(object): @classmethod def get_sub(cls): """动态获取继承的子类""" rel_path = os.path.relpath(__file__) # 相对路径,可能项目的根目录会有 .., eg: '..\\..\\hdyplus\\app\\services\\service_utils\\new\\api_parse.py' package, file_name = os.path.split(rel_path) package_list = [str(i) for i in package.split(os.path.sep) if i != '..'] package = '.'.join(package_list) current_path = os.path.dirname(os.path.abspath(__file__)) current_files = [f.split('.')[0] for f in os.listdir(current_path) if isfile(join(current_path, f))] for f in current_files: try: module = importlib.import_module('.%s' % f, package=package) for name, sub in inspect.getmembers(module): if inspect.isclass(sub): # 类别是class,并且父类是A if sub_class.__base__ == cls: print(sub.__name__)except Exception as e:pass