Python动态类名
可能重复的问题:
动态加载Python模块
Python:如何动态地给类添加属性?
我有一个字典,里面存着文件名和类名,我该怎么导入这些类名,并且怎么创建这些类呢?
举个例子:
classNames = { 'MCTest':MCTestClass}
我想导入MCTest,并创建MCTestClass。
2 个回答
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(...)
6
你需要使用 __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()