2011-09-02 55 views
0

可能重复:
Dynamic loading of python modules
python: How to add property to a class dynamically?Python的动态类名

我有一个文件名和类名如何导入这个类的名字,我怎么可以创建一个字典这个班?

例子:

classNames = { 'MCTest':MCTestClass} 

我要导入的MCTest并创建MCTestClass。

+1

我完全不明白你在说什么。你可以重新解释一下你的问题,也许可以举一些例子说明你的字典中有什么,以及之后你想要什么?这是什么“文件名”? –

+0

我假定他有模块和类名作为字符串,并且想要实例化类 – tauran

+0

是的,正确。感谢您的帮助 –

回答

5

您必须使用__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 ...> 

从巴兹实例化一个类,你应该能够做到:

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

如果我不知道类名,但类名与模块名相同,我怎么能创建班级? –

+0

使用'getattr'从模块中获取类(请参阅我的更新) – tauran

1

来自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(...)