python之__import__

昨天初步研究了一下python的__import__,发现很多东西。我觉得很难理解。

目录结构:

manager.py

/dbpackage

    models.py

运行manager.py shell(如果用过django的话,应该知道怎么回事)

>>> mod=__import__("dbpackage")
>>> mod
<module 'dbpackage' from 'E:/testProgram/DynamicImport/src/dynamicTest/dbpackage/__init__.pyc'>

这个好理解,导入包dbpackage

>>> mod=__import__("dbpackage.models")
>>> mod
<module 'dbpackage' from 'E:/testProgram/DynamicImport/src/dynamicTest/dbpackage/__init__.pyc'>

这个就不好理解,为什么没导入models?原来要导入models要这样做:

>>> mod=__import__("dbpackage.models",{},{},["models"])
>>> mod
<module 'dbpackage.models' from 'E:/testProgram/DynamicImport/src/dynamicTest/dbpackage/models.pyc'>

这样才可以导入models模块

需要进一步弄懂,查了一下官方文档,是这样写的:

When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned,not the module named by name. However, when a non-emptyfromlist argument is given(真的只要不是空就可以了,你可以随便写,比如["a"]), the module named byname is returned. This is done for compatibility with the bytecode generated for the different kinds of import statement; when using "import spam.ham.eggs", the top-level packagespam must be placed in the importing namespace, but when using "from spam.ham import eggs", thespam.ham subpackage must be used to find the eggs variable. As a workaround for this behavior, usegetattr() to extract the desired components. For example, you could define the following helper:

def my_import(name):
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值