Module
- A .py file is a module
- maintainability
- Scalability
- Each module has its own namespace
Module classification
- Built-in standard modules
- Third-party open source modules
- custom module
module call
- import module
- from module import xx
- from module.xx.xx import xx as rename
- from module.xx.xx import *
module search path
- sys.path
- Find the module name in the order of the path list, and stop as soon as it is found
- Empty elements represent the current directory, so custom current directory modules will be imported first
import sys
print(sys.path)
['',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python36.zip',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload',
'/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages']
Package
- Put related modules in a folder, this folder is called a package
- The __init__.py file must exist in the folder, which is used to identify the folder as a package
Import across modules
- Add environment variables, add the parent path to sys.path, and search from the parent
import sys ,os
# __file__的是打印当前被执行的模块.py文件相对路径,注意是相对路径
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from proj import settings
Absolute & Relative Imports
- ..upper path
- .current path