品易云推流 关闭
文章详情页
文章 > Python基础教程 > python Package如何设置文件入口

python Package如何设置文件入口

头像

小妮浅浅

2021-06-05 09:57:573376浏览 · 0收藏 · 0评论

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电脑。

关注

关注公众号,随时随地在线学习

本教程部分素材来源于网络,版权问题联系站长!

底部广告图