In the development process of computer programs, as more and more program codes are written, the code in a file will become longer and longer, making it less and less easy to maintain.
In order to write maintainable code, we group many functions and put them into different files. In this way, each file contains relatively less code and a lot of code. Programming languages all use this way of organizing code. In Python, a .py file is called a module (Module).
What are the benefits of using modules? (Recommended learning: Python video tutorial)
The biggest benefit is that it greatly improves the maintainability of the code. Second, you don't have to start from scratch when writing code. When a module is written, it can be referenced elsewhere. When we write programs, we often refer to other modules, including Python's built-in modules and modules from third parties.
Using modules can also avoid conflicts between function names and variable names. Functions and variables with the same name can exist in different modules. Therefore, when we write the module ourselves, we do not have to consider that the name will conflict with other modules. But also be careful not to conflict with built-in function names.
You may also think, what if different people write modules with the same name? In order to avoid module name conflicts, Python has introduced a method of organizing modules by directory, called Package (Package).
A package is a higher-level concept than a module. A module is generally a file, and a package is a directory. A package can contain many modules.
All of the package is defined in the init.py file, and all of the module is defined at the beginning of the module file
The following packages are represented by P and modules are represented by M Representation, the method is represented by F
在Python中引入模块可以用 import M from M import * from M import F 引入包的方式可以是 import P from P import M from P import * from P.M import F from P1.P2.M import F
In addition, the init.py file of the package cannot be missing.
For more Python related technical articles, please visit the Python Tutorial column to learn!
The above is the detailed content of The difference between python modules and packages. For more information, please follow other related articles on the PHP Chinese website!