可能重复:
Dynamic loading of python modules
python: How to add property to a class dynamically?
我有一个包含文件名和类名的字典如何导入这个类名,我该如何创建这个类?
示例:
classNames = { 'MCTest':MCTestClass}
我想导入MCTest并创建MCTestClass。
答案 0 :(得分:5)
您必须使用__import__
功能:
http://docs.python.org/library/functions.html#import
来自doc页面的示例:
>>> 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()
答案 1 :(得分: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(...)