日志 9.4 2008

昨天初步研究了一下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-empty fromlist argument is given(真的只要不是空就可以了,你可以随便写,比如["a"]), the module named by name 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 package spam must be placed in the importing namespace, but when using "from spam.ham import eggs", the spam.ham subpackage must be used to find the eggs variable. As a workaround for this behavior, use getattr() 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

你可能感兴趣的:(python,django,UP)