Python - 从导入的模块中获取类的类

时间:2011-05-23 09:11:42

标签: python

我正在尝试从具有动态名称的文件中导入类。这是我的文件导入程序:

def get_channel_module(app, method):
    mod_name = 'channel.%s.%s' % (app, method)
    module = __import__(mod_name, globals(), locals(), [method])
    return module

这会导入特定的python文件,例如some_file.py,如下所示:

class SomeClassA(BaseClass):
    def __init__(self, *args, **kwargs):
        return

class SomeClassB():
    def __init__(self, *args, **kwargs):
        return

我想要做的只是从导入的文件中返回扩展BaseClass的类,所以在这个实例中,SomeClassA。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:7)

您可以通过issubclass

检查模块中的符号来执行此操作
def get_subclass(module, base_class):
    for name in dir(module):
        obj = getattr(module, name)
        try:
            if issubclass(obj, base_class):
                return obj
        except TypeError:  # If 'obj' is not a class
            pass
    return None

答案 1 :(得分:4)

导入模块后,迭代它的命名空间,查找作为BaseClass子类的类对象。

klasses = [c for c in module.__dict__.values() if isinstance(c, type)]
base_subclasses = [c for c in klasses if issubclass(c, BaseClass]
## or as a single list comprehension
base_subclasses = [c for c in module.__dict__.values() if isinstance(c, type) and issubclass(c, BaseClass)]