Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python动态类名_Python_Dynamic - Fatal编程技术网

Python动态类名

Python动态类名,python,dynamic,Python,Dynamic,可能重复: 我有一个带有文件名和类名的字典。我怎样才能导入这个类名,怎样才能创建这个类 例如: classNames = { 'MCTest':MCTestClass} 我想导入MCTest并创建MCTestClass。您必须使用\uuuuuu导入\uuuu功能: 文档页面中的示例: >>> import sys >>> name = 'foo.bar.baz' >>> __import__(name) <module 'foo

可能重复:

我有一个带有文件名和类名的字典。我怎样才能导入这个类名,怎样才能创建这个类

例如:

classNames = { 'MCTest':MCTestClass}

我想导入MCTest并创建MCTestClass。

您必须使用
\uuuuuu导入\uuuu
功能:

文档页面中的示例:

>>> import sys
>>> name = 'foo.bar.baz'
>>> __import__(name)
<module 'foo' from ...>
>>> baz = sys.modules[name]
>>> baz
<module 'foo.bar.baz' from ...>
从turbogears.util:

def load_class(dottedpath):
    """Load a class from a module in dotted-path notation.

    E.g.: load_class("package.module.class").

    Based on recipe 16.3 from Python Cookbook, 2ed., by Alex Martelli,
    Anna Martelli Ravenscroft, and David Ascher (O'Reilly Media, 2005)

    """
    assert dottedpath is not None, "dottedpath must not be None"
    splitted_path = dottedpath.split('.')
    modulename = '.'.join(splitted_path[:-1])
    classname = splitted_path[-1]
    try:
        try:
            module = __import__(modulename, globals(), locals(), [classname])
        except ValueError: # Py < 2.5
            if not modulename:
                module = __import__(__name__.split('.')[0],
                    globals(), locals(), [classname])
    except ImportError:
        # properly log the exception information and return None
        # to tell caller we did not succeed
        logging.exception('tg.utils: Could not import %s'
            ' because an exception occurred', dottedpath)
        return None
    try:
        return getattr(module, classname)
    except AttributeError:
        logging.exception('tg.utils: Could not import %s'
            ' because the class was not found', dottedpath)
        return None

我完全不明白你在说什么。你能重新表述一下你的问题吗?也许可以举一些例子说明你的字典里有什么,以及你以后想要什么?这个“文件名”是什么?我假设他将模块和类名作为字符串,并希望实例化类是的,没错。感谢您的帮助如果我不知道类名,但类名与模块名相同,我如何创建类?使用
getattr
从模块获取类(请参阅我的更新)
def load_class(dottedpath):
    """Load a class from a module in dotted-path notation.

    E.g.: load_class("package.module.class").

    Based on recipe 16.3 from Python Cookbook, 2ed., by Alex Martelli,
    Anna Martelli Ravenscroft, and David Ascher (O'Reilly Media, 2005)

    """
    assert dottedpath is not None, "dottedpath must not be None"
    splitted_path = dottedpath.split('.')
    modulename = '.'.join(splitted_path[:-1])
    classname = splitted_path[-1]
    try:
        try:
            module = __import__(modulename, globals(), locals(), [classname])
        except ValueError: # Py < 2.5
            if not modulename:
                module = __import__(__name__.split('.')[0],
                    globals(), locals(), [classname])
    except ImportError:
        # properly log the exception information and return None
        # to tell caller we did not succeed
        logging.exception('tg.utils: Could not import %s'
            ' because an exception occurred', dottedpath)
        return None
    try:
        return getattr(module, classname)
    except AttributeError:
        logging.exception('tg.utils: Could not import %s'
            ' because the class was not found', dottedpath)
        return None
cls = load_class('package.module.class')
obj = cls(...)