python如何做动态加载_如何动态加载Python类

如果您不想自己滚动,那么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)."""

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值