• 技术文章 >Python技术 >Python基础教程

    python Package如何设置文件入口

    小妮浅浅小妮浅浅2021-06-05 09:57:57原创3193

    1、说明

    (1)Python 中的包(Package)则是模块的文件夹,往往由 __init__.py 指明某个文件夹为包;

    (2)Package可以为某个目录下所有的文件设置统一入口。

    2、实例

    someDir/
        main.py
        subModules/
            __init__.py
            subA.py
            subSubModules/
                __init__.py
                subSubA.py
     
    # subA.py
     
    def subAFun():
        print('Hello from subAFun')
     
    def subAFunTwo():
        print('Hello from subAFunTwo')
     
    # subSubA.py
     
    def subSubAFun():
        print('Hello from subSubAFun')
     
    def subSubAFunTwo():
        print('Hello from subSubAFunTwo')
     
    # __init__.py from subDir
     
    # Adds 'subAFun()' and 'subAFunTwo()' to the 'subDir' namespace
    from .subA import *
     
    # The following two import statement do the same thing, they add 'subSubAFun()' and 'subSubAFunTwo()' to the 'subDir' namespace. The first one assumes '__init__.py' is empty in 'subSubDir', and the second one, assumes '__init__.py' in 'subSubDir' contains 'from .subSubA import *'.
     
    # Assumes '__init__.py' is empty in 'subSubDir'
    # Adds 'subSubAFun()' and 'subSubAFunTwo()' to the 'subDir' namespace
    from .subSubDir.subSubA import *
     
    # Assumes '__init__.py' in 'subSubDir' has 'from .subSubA import *'
    # Adds 'subSubAFun()' and 'subSubAFunTwo()' to the 'subDir' namespace
    from .subSubDir import *
    # __init__.py from subSubDir
     
    # Adds 'subSubAFun()' and 'subSubAFunTwo()' to the 'subSubDir' namespace
    from .subSubA import *
     
    # main.py
     
    import subDir
     
    subDir.subAFun() # Hello from subAFun
    subDir.subAFunTwo() # Hello from subAFunTwo
    subDir.subSubAFun() # Hello from subSubAFun
    subDir.subSubAFunTwo() # Hello from subSubAFunTwo

    以上就是python Package设置文件入口的方法,希望对大家有所帮助。更多Python学习指路:python基础教程

    本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

    专题推荐:python package
    上一篇:python使用enum进行枚举的比较 下一篇:python如何实现条件选择

    相关文章推荐

    • python packages是什么意思

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网