Python 动态类名

发布于 2024-12-02 09:18:12 字数 460 浏览 0 评论 0原文

可能的重复:
Python模块的动态加载
python:如何动态向类添加属性?

我有一个包含文件名和类名的字典,如何导入此类名称以及如何创建此类?

示例:

classNames = { 'MCTest':MCTestClass}

我想导入 MCTest 并创建 MCTestClass。

Possible Duplicate:
Dynamic loading of python modules
python: How to add property to a class dynamically?

I have a dictionary with the filename and class names how can I import this class names and how can I create this classes?

Example:

classNames = { 'MCTest':MCTestClass}

I want to import the MCTest and create the MCTestClass.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

硬不硬你别怂 2024-12-09 09:18:12

您必须使用 __import__ 函数:

http://docs. python.org/library/functions.html#import

来自文档页面的示例:

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

要从 baz 实例化一个类,您应该能够执行以下操作:

>>> SomeClass = getattr(baz, 'SomeClass')
>>> obj = SomeClass()

You have to use the __import__ function:

http://docs.python.org/library/functions.html#import

Example from doc page:

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

To instantiate a class from baz you should be able to do:

>>> SomeClass = getattr(baz, 'SomeClass')
>>> obj = SomeClass()
断肠人 2024-12-09 09:18:12

来自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

像这样使用它:

cls = load_class('package.module.class')
obj = cls(...)

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

use it like this:

cls = load_class('package.module.class')
obj = cls(...)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文