Home > Article > Backend Development > What is a module? Introduction to modules in Python
This article brings you the content about what is a module? The introduction of modules in Python has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
In Python, a .py file is called a module.
So what are the benefits of using modules?
(1) Improves the maintainability of the code.
(2) The code does not have to be started from scratch. After a module is written, it can be applied elsewhere.
(3) You can avoid conflicts between function names and variable names. The same function names and variables can be stored in different modules, but be careful not to conflict with built-in function names.In order to avoid module name conflicts, python has introduced a method to prevent module conflicts by directory, called packages (python package).
A file abc.py is a module named abc, and a file xyz.py is a module named xyz. If the module names abc and xyz conflict with other modules, we can organize the modules through different packages to avoid module conflicts.
can be:
↓ mycompany # 按目录存放 _init_.py # 模块名:mycompany abc.py # 模块名:mycompany.abc xyz.py # 模块名:mycompany.xyz
After the package is introduced, as long as the top-level package name does not conflict with others, then all modules will not conflict with others.
There will be an _init_.py file in each package directory. This file must exist, otherwise python will treat this directory as a normal directory instead of a package.
_init_.py can be an empty file, or it can have python code, because _init_.py itself is a module.
Python has many very useful built-in modules. As long as they are installed, these modules can be imported and used immediately through import.
For example, the following small program: use the self-built sys module to write a hello module hello.py.
# !/usr/bin/env python # -1- # -*-coding:utf-8 -*- # -2- _author_ = 'xionglp' # 使用_author_变量把作者写进去 import sys def test(): args = sys.argv if len(args) == 1: print ('hello,world!') elif len(args) ==2: print('hello,%s !'% args[1]) else: print('too many arguments!') if __name__ == '__main__': test()
Description:
Comment# -1-: Let the .py file run directly on unix/linux/mac
Comment# -2-: .py file Use standard UTF-8 encoding
import sys: Import the sys module. You can then use the sys variable to access all functions of the sys module.
The sys module has an argv variable, which uses a list to store all the parameters of the command line. argv has at least one element because the first argument is always the name of the .py file.
When the hello.py file is run on the command line, the python interpreter sets a special variable __name__ to __main__. If the module is imported elsewhere, the if judgment will fail, that is, the if will only take effect when this module is run alone. So this if test allows a module to execute some additional code when run through the command line, most commonly running tests.
Import the module in the interactive environment (cmd):
>>> import hello >>> hello.test() hello, world!
In addition to Python’s own packages, You can also install third-party modules. Third-party package installation is completed through the package management tool pip.
Generally speaking, third-party libraries will be registered on Python’s official pypi.python.org website. Therefore, to install a third-party library, you must first know the name of the library, which can be searched on the official website or pypi. For example, the name of Pillow is Pillow, so the command to install Pillow is: pip install Pillow
Step 1: Find easy_install.exe in the path to install Python, for example: D:PythonScripts
Step 2 : Open cmd and enter the installation command: easy_install.exe pip (pip installation is successful)
Step 3: Execute pip under cmd and enter the command: pip install pillow
as follows:
After successful installation, you can use Pillow. Other commonly used third-party libraries include: MySQL driver, NumPy library for scientific computing, etc.
pip upgrade:
When using pip to install, sometimes it will prompt that the version of pip is too low and needs to be upgraded. The prompt will give you the statement to be executed, just follow the prompt.
Execution command: python –m pip install –upgrade pip
We can also import modules written by ourselves. When we try to load a module, Python will search for the corresponding .py file in the specified path. If it cannot be found, an error will be reported, for example:
By default, the Python interpreter will search the current directory, all installed built-in modules and third-party modules. The search path is stored in the path variable of the sys module:
>>>import sys >>>sys.path
If we want to add ourselves There are two methods for searching directories:
Method 1: Directly modify sys.path and add the directory to be searched. This method is modified during runtime and will become invalid after the run is completed.
>>> import sys >>> sys.path.append('/Users/xionglp/my_py_scripts')
法二:设置环境变量PYTHONPATH,该环境变量的内容会被自动添加到模块搜索路径中。设置方式与设置Path环境变量类似。注意只需要添加你自己的搜索路径,Python自己本身的搜索路径不受影响。
【补充点能量】if __name__ =="__main__":
__name__:为系统变量,有两个取值。当模块是被调用执行时,取值为模块的名字;当模块是直接执行时,则该变量取值为__name__。
if __name__ == "__main__"实现的功能:可以让模块既可以导入到别的模块中用,也可以自己执行。
英文解释说:make a script both importable and executeable例如:新建模块atest.py
# !/usr/bin/env python3 # -*- coding:utf-8 -*- 'a test module' def addFunc(a, b): return a + b print('a_test_module\'s result is ', addFunc(1, 1))
新建模块anothertest.py
# !/usr/bin/env python3 # -*- coding :utf-8 -*- 'another test module' import atest print('调用another test module模块执行的结果时:',atest.addFunc(12,23))
运行:
D:\Python_project>python atest.py a_test_module's result is 2 D:\Python_project>python anothertest.py a_test_module's result is 2 调用another test module模块执行的结果时: 35
说明:当运行anothertest.py的时候,先运行了atest.py,再运行anothertest.py。
若不希望出现atest的内容,python提供了一个系统变量:__name__。可以把被调用的测试代码写在if语句里,当调用该module时,此时的__name__取值为该模块的名字,所以if判断为假,不执行后续代码如下:
if __name__ == '__main__':` print ('atest的计算结果:',addFunc(1,1))
则运行结果为:
D:\Python_project>python anothertest.py 调用another test module模块执行的结果时: 35
此时我们就得到了预期结果,不输出多余的结果。
The above is the detailed content of What is a module? Introduction to modules in Python. For more information, please follow other related articles on the PHP Chinese website!