41

I have class called 'my_class' placed in 'my_module'. And I need to import this class. I tried to do it like this:

import importlib
result = importlib.import_module('my_module.my_class')

but it says:

ImportError: No module named 'my_module.my_class'; 'my_module' is not a package

So. As I can see it works only for modules, but can't handle classes. How can I import a class from a module?

4

2 回答 2

60

它期望my_module是一个包含名为'my_class'. 如果您需要动态导入类或一般属性,只需getattr在导入模块后使用:

cls = getattr(import_module('my_module'), 'my_class')

另外,是的,它只适用于模块。记住importlib.import_module是内部importlib.__import__函数的包装器。它不提供与完整语句相同数量的功能,完整import语句加上from,对导入的模块执行属性查找。

于 2017-01-16T14:02:52.067 回答
4
import importlib
import logging

logger = logging.getLogger(__name__)


def factory(module_class_string, super_cls: type = None, **kwargs):
    """
    :param module_class_string: full name of the class to create an object of
    :param super_cls: expected super class for validity, None if bypass
    :param kwargs: parameters to pass
    :return:
    """
    module_name, class_name = module_class_string.rsplit(".", 1)
    module = importlib.import_module(module_name)
    assert hasattr(module, class_name), "class {} is not in {}".format(class_name, module_name)
    logger.debug('reading class {} from module {}'.format(class_name, module_name))
    cls = getattr(module, class_name)
    if super_cls is not None:
        assert issubclass(cls, super_cls), "class {} should inherit from {}".format(class_name, super_cls.__name__)
    logger.debug('initialising {} with params {}'.format(class_name, kwargs))
    obj = cls(**kwargs)
    return obj
于 2018-12-06T16:11:35.200 回答