如果您不想自己滚动,那么pydoc模块中有一个函数可以执行以下操作:from pydoc import locate
my_class = locate('my_package.my_module.MyClass')
与这里列出的其他方法相比,这种方法的优点是locate将在提供的点路径上找到任何python对象,而不仅仅是模块内的对象。e、 g.my_package.my_module.MyClass.attr。
如果你好奇他们的食谱是什么,这里有一个功能:def locate(path, forceload=0):
"""Locate an object by name or dotted path, importing as necessary."""
parts = [part for part in split(path, '.') if part]
module, n = None, 0
while n < len(parts):
nextmodule = safeimport(join(parts[:n+1], '.'), forceload)
if nextmodule: module, n = nextmodule, n + 1
else: break
if module:
object = module
else:
object = __builtin__
for part in parts[n:]:
try:
object = getattr(object, part)
except AttributeError:
return None
return object
它依赖于pydoc.safeimport功能。以下是相关文件:"""Import a module; handle errors; return None if the module isn't found.
If the module *is* found but an exception occurs, it's wrapped in an
ErrorDuringImport exception and reraised. Unlike __import__, if a
package path is specified, the module at the end of the path is returned,
not the package at the beginning. If the optional 'forceload' argument
is 1, we reload the module from disk (unless it's a dynamic extension)."""