You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中通过包路径字符串初始化对象?

通过字符串路径动态初始化Python类对象

如果已经有完整的类路径字符串(比如"component.sub_fold.package.class_name"),可以通过以下几种方式动态初始化对象:

方法一:使用标准库importlib(推荐)

这是Python官方推荐的动态导入方式,逻辑清晰且易于维护:

import importlib

# 你的完整类路径字符串
full_class_path = "component.sub_fold.package.class_name"

# 拆分模块路径和类名:从最后一个点分割
module_path, class_name = full_class_path.rsplit('.', 1)

# 动态导入模块
target_module = importlib.import_module(module_path)

# 从模块中获取目标类
target_class = getattr(target_module, class_name)

# 初始化对象
obj = target_class()

方法二:使用内置__import__函数

这是更底层的导入方式,语法相对简洁但可读性稍弱:

full_class_path = "component.sub_fold.package.class_name"

module_path, class_name = full_class_path.rsplit('.', 1)
# fromlist参数设为非空值,确保返回的是最底层的子模块
target_module = __import__(module_path, fromlist=[class_name])

target_class = getattr(target_module, class_name)
obj = target_class()

注意事项

  • 确保你的模块路径在Python的sys.path搜索范围内,否则会抛出ModuleNotFoundError
  • 类名字符串必须和目标类的名称完全一致,否则getattr会抛出AttributeError

内容的提问来源于stack exchange,提问作者taichi_tiger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 12:42:03