获取`package.module.Class'的Python方法`

获取`package.module.Class'的Python方法`,python,string,import,module,Python,String,Import,Module,给定一个格式为'package.module.Class'的字符串,Python中是否有直接获取类对象的简单方法(假设模块尚未导入) 如果不是,那么将'package.module'部分与'Class'部分分开的最干净的方法是什么,\uuuuu导入模块()然后从中获取类 试试这样的方法: import sys def str_to_obj(astr): ''' str_to_obj('scipy.stats.stats') returns the associated modul

给定一个格式为
'package.module.Class'
的字符串,Python中是否有直接获取类对象的简单方法(假设模块尚未导入)


如果不是,那么将
'package.module'
部分与
'Class'
部分分开的最干净的方法是什么,
\uuuuu导入模块()
然后从中获取类

试试这样的方法:

import sys
def str_to_obj(astr):
    '''
    str_to_obj('scipy.stats.stats') returns the associated module
    str_to_obj('scipy.stats.stats.chisquare') returns the associated function
    '''
    # print('processing %s'%astr)
    try:
        return globals()[astr]
    except KeyError:
        try:
            __import__(astr)
            mod=sys.modules[astr]
            return mod
        except ImportError:
            module,_,basename=astr.rpartition('.')
            if module:
                mod=str_to_obj(module)
                return getattr(mod,basename)
            else:
                raise
def import_obj(path):
    path_parts = path.split(".")
    obj = __import__(".".join(path_parts[:-1]))
    path_remainder = list(reversed(path_parts[1:]))
    while path_remainder:
        obj = getattr(obj, path_remainder.pop())
    return obj

这将适用于任何可以从模块中获取属性的内容,例如模块级函数、常量等。

模块中的下划线、u、basename是否有任何特殊含义,或者它只是对象的名称?@Paul:
'scipy.stats.stats.chisquare'.rpartition(')。
返回一个三元组:
('scipy.stats.stats','.'和'chisquare')
。中间的字符串只是垃圾。下划线,
,是有效的变量名,通常用于指示变量是垃圾。尽管我看到它也用于其他用途。。。