table of Contents
Modular
Python is only one type of object modules
Module module, refers Python source code files
Bag package, refer to the Directory Module organization together packages and package of the same name and its related files
Four forms module
- Built-in module: Python interpreter module comes
- pip install a module: pip install the module name
- Custom modules: custom module
- package
Import statement
Import of non-top-level module, only its top-level module name is added to the local term space. Imported modules must use the fully qualified name to access.
If used as, as the name of the module to bind directly imported objects and added to the local name space noun.
- Find the from clause specified module is loaded and initialized (not imported)
- For the import clause name
- From module to check whether the clauses introduced the name attribute
- If there are, then try the same name as the name of the module to import submodule
- Not found, an exception is thrown Import Error
- Song name to save space in local terms, if used as statements, use the name as the latter clause
Custom Modules
The module name is the file name
The module name must conform to the requirements of identifiers
Do not use the system module name, to avoid conflict
Usually all lowercase module names, separated by underscores
Module search order
From the current -> Local -> Global -> Built-in
The main program directory, run the main script directory where
PYTHONPATH directory, the directory also set the environment variable PYTHONPATH search path module
Standard library catalog, Pythoon own library modules directory where
Modules run
import time
#1. 开辟内存空间,内存空间命名为time
# 2. 把time.py中的所有代码读入名称空间,然后运行
# 3. 通过time.方法名使用time模块中的方法
Advantages: Never conflict
Disadvantages: Import trouble
from time import sleep
# 1. 开辟内存空间,内存空间命名为time
# 2. 把time.py中的所有代码读入名称空间,然后运行
# 3. 把sleep()读入import和from...import.py中,因此可以直接使用方法名
from time import * #表示导入time下所有方法
Advantages: easy to call
Disadvantages: prone to conflict
if __name__ == '__main__':
Syntactically function tests used in modules,
Which, when run the file to the current file, __ name__ parameter defaults __main__; when the module is run outside to call the file, __ name__ default value of the parameter module name (it means default can be changed, but not necessary)
- This function test function modules: function module inside this test, class
- Avoiding side effects master switching module: top code, no encapsulation, no master module using a new problem once the master module, this module is to be introduced, since there is no source code package, performed together.