代码之家  ›  专栏  ›  技术社区  ›  Guy

Python:导入包含包

  •  57
  • Guy  · 技术社区  · 16 年前

    在驻留在包中的模块中,我需要使用在 __init__.py

    导入 __init__ 模块内部不会导入包,而是导入名为的模块 __初始化__ ,导致两个不同名字的东西的副本。。。

    有没有蟒蛇式的方法可以做到这一点?

    5 回复  |  直到 11 年前
        1
  •  46
  •   Brian Clapper    9 年前

    from . import foo
    

    引用 http://docs.python.org/tutorial/modules.html#intra-package-references :


    从Python2.5开始,除了上面描述的隐式相对导入之外,还可以使用import语句的from module import name形式编写显式的相对导入。这些显式的相对导入使用前导点指示相对导入中涉及的当前包和父包。例如,从周围的模块中,您可以使用:

    from . import echo
    from .. import formats
    from ..filters import equalizer
    
        2
  •  23
  •   mipadi    16 年前

    __init__.py 文件,并放入该包中的另一个模块中。然后您可以轻松地将该函数导入到其他模块中。如果需要,可以在 将导入该函数的文件(当导入包时)。

        3
  •  5
  •   Eli Courtwright    16 年前

    如果包名为 testmod testmod/__init__.py 并且在你的模块中 submod.py 文件,你应该可以说 import testmod 使用testmod中定义的任何东西。

        4
  •  1
  •   cdleary    16 年前

    import __init__ as top
    top.some_function()
    

    或者也许?:

    from __init__ import some_function
    some_function()
    
        5
  •  1
  •   Esteban Küber    14 年前

    在Django,文件管理.py有 from django.core.management import execute_manager ,但是 execute_manager __init__.py 模块 management 目录。