Module:
A module is a file containing Python code, a file is a module
Why use a module
1. Now the program development files are relatively large, are placed in a file maintenance inconvenient, split into multiple files for easy maintenance and management
2. Module can increase the reuse rate of code
3. The module can be used as a namespace
How to define your own module
The module itself is a file, all the PY code can be written directly in the file, but when we develop the common module, it is best to write the content in the module
Properties in a variable module
Functions separate functions
class similar function combinations
Module test code is temporarily used and will not be executed when imported
Test code:
The test code is often used to test the functionality of the module while it is being developed, but the test code is used only during development and testing, and is not intended to be run as a module import, and requires the use of the name special variable to manipulate
if __name__ = =' __main__ ':#测试代码区域 (the test code is executed only when the current file is running directly, and will not be executed as a module import) __name__ when the current file is run directly, the result is __main__ __name__ is the module name when the file is imported as a module
how modules are imported
1.import Module Name
2.import Module name as Alias
3.from Module Import function/class
4.from Module Import *
Storage of Modules
Import SYS
Sys.path #获取当前搜索路径的列表
sys.path.append (custom path) #将自定义的路径添加到列表中
load order of modules
steps to import a module operation:
1. Detect if the current module has been loaded in memory, and if loaded, use the loaded module directly
2. If the current module is not loaded in memory, search Python's built-in module
3. If the module is not changed in the current built-in module, find and load the module according to the search path
Package:
A package is a folder that is used to store files, which are modules, which can also be stored in packages.
the structure of the package:
|---- __init__.py 包的标志文件|---- 模块1|---- 模块2|---- 子包(文件夹)|-----|----__init__.py|---- |----子模块1|---- |----子模块2
包的导入和使用
1.import 包.模块
2.import 包.模块 as 别名
3.from 包.模块 import 函数或者类或者属性
4.from 包.模块 import *
包的相互调用问题
如果在当前模块中需要调用其他模块或者包的内容时,可以直接使用import导入对应的包和模块你,就可以加载进来使用,import会搜索包和模块对应的搜索路径
注:
__init__.py 文件中添加内容
给inint文件添加内容 就相当于给包添加内容 包可以被导入使用
__all__特殊变量的用户
1. 在__init__.py文件中,如果没有__all__变量,那么使用from包import * 仅导入__init__.py中定义的方法和类及其他内容
2. 在init.py文件中,如果定义all变量,那么使用from包import * 则会导入指定的所有模块,而忽略init.py文件中的信息
__all__ = [‘模块’,‘子包’....] #必须是列表
Python Learning---modules and packages