We first create a package. The so-called package is to create a directory with an __init__.py file.
We create a mypack directory under the common directory, and create the following 3 .py files in this directory:
# mypack/__init__.py
print("mypack init")
def init():
print("mypack init function")
# mypack/video.py
print("video module")
def view():
print("video view")
# mypack/audio.py
print("audio module")
def play():
print("play audio")
Test file testpack.py: An
error was reported, the package myapck could not be found, because the package is not in the same level directory as the current source file, what should I do?
Add the search path through sys.path.insert:
# 系统模块
import sys
# print(sys.path)
# 添加模块的查找路径,包的查找路径和模块的是一致的
sys.path.insert(0, "../common/")
Then you can call the initialization function in __init__.py, but an error is found in the running file testpack.py:
Import the modules in the package:
- We can't just import the package, otherwise the module cannot be found, so we need to import the specific module name in the package:
There is also an import method:
Only the namespace of the package mypack is introduced, which means that everything under the mypack namespace is included in the namespace of our current main module __main__:
# 还有一种导入方法
from mypack import audio
audio.play()
- If we want to introduce the entire audio directly into the namespace, what should we do?
# 引入包和模块的命名空间
# from mypack.audio import *
from mypack.audio import play
play()
Note the *asterisk:
from mypack import *
This method does not import all the modules of the package, that is, video and audio are not imported. This method only imports all the functions and members in __init__.py.
- What if I want to directly quote all modules in the package and all that should be quoted?
You need to define a variable __all__ in __init__.py, and then you can know which modules to import when Python executes to from mypack import *:
# mypack/__init__.py
print("mypack init")
# import * 的时候需要载入的模块
__all__ = ["audio", "video", "openGL"]
def init():
print("mypack init function")
Modify the testpack.py file as follows:
# 子包 mypack/sub/pydir.py
def pydir():
print("pydir")
The package contains multiple modules, and the modules contain multiple functions, classes, and variables.
Package -> Module -> Function, Class, Variable