Zero basic learning Python|Python advanced learning eighth day--module

Author Homepage: Programming Compass

About the author: Java, front-end, and Python have been developed for many years, and have worked as a senior engineer, project manager, and architect

Main content: Java project development, graduation design development, interview technology arrangement, latest technology sharing

Favorites, likes, don't get lost, it's good to follow the author

Get the source code at the end of the article

​# Python advanced learning

Second, the module

Module is a very important design in Python. It is mainly used to encapsulate some reusable code for others or yourself. Functions are used to encapsulate code, so a module can contain multiple functions to be used by others. We encapsulate some encapsulated functions and variables into a .py file. When others use it, they can use the import statement to import it and use it directly ,Very convenient. Just like we import java classes. Python provides a large number of built-in modules, and there are also many third-party module libraries for us to use, and we can also customize modules for use.

2.1 Create a module

1. The file name suffix must be .py

2. The module name should not be the same as the name in the built-in module library

Example: Encapsulate the function we defined into the mathadd.py file

def add(a,b):
   return a+b

2.2 Import and use modules

1. Use import module [as alias]

If the module name is relatively long, you can use as alias to set the name and use it through an alias, otherwise you can not use it. But when calling a function or variable in a module, you need to add the module name. If you import multiple modules at the same time, it is recommended to import them separately, or you can import them all at once, separated by commas.

Example:

import mathadd

result = mathadd.add(1,2)
print(result)

2. Use from ... import to import modules

Using this method to import and use, when importing variables or functions in the module, there is no need to add the function name. from modules import functions

from mathadd import add

result = add(1,2)
print(result)
from mathadd import *   #表示导入模块中所有的元素

2.3 Module search directory

When we use import to import a module, how does it search for this module and import it. By default, the search is done in the following order.

(1) Search in the current directory (that is, the directory where the python script file is executed)

(2) Search in each directory under PYTHONPATH (environment variable).

(3) Search in the default installation directory of Python.

The specific locations of the above directories are stored in the sys.path variable of the standard module sys, and can be checked by outputting the specific directory locations through the following code:

import sys
print(sys.path)

If the module we want to import is not in the path variable, an error message will indicate that the imported module does not exist.

We can add the specified directory to sys.path in the following three ways as needed.

1. Temporary addition: This method is valid only in the currently executing window, and becomes invalid when the window is closed.

import sys
sys.path.append('要添加的目录')

2. Add .pth file (recommended)

Find the Lib\site-packages subdirectory in the currently installed Python, create a file with the extension .pth, the file name is arbitrary, and just write the directory to be added into this file. This method is only valid for the current version of python.

3. Add to the PYTHONPATH environment variable

In the environment variable setting of the current operating system, add or edit the PYTHONPATH environment variable, and add or append the directory to be added to take effect. This method is effective for all Python versions.

2.4 Run as the main program

Let's change the case just now: add an output statement in mathadd.py

def add(a,b):
    return a+b

print("我来了.....")

Import the module and execute the method:

from mathadd import add

result = add(1,2)
print(result)

Output result:

我来了.....
3

We only want to call add, but the print statement is also executed. When the code in the calling module is executed, all executable code in the module will be executed. This is not what we want, how to solve it?

Just add an if statement to the place where the code is executed in the original module to judge whether the main program is executed:

def add(a,b):
    return a+b
if __name__ == '__main__': 
    print("我来了.....")

Each module has a _ _ name _ _ that records the module name. If a module is not imported into other modules or files to be executed, then it is executed in the top-level module _ _ main _ _, and the judgment is also That is, if you run mathadd.py directly, this code can be executed, otherwise it will not be executed.

2.5 Packages in python

Packages are mainly used by related modules that store definitions in different categories, and can also effectively avoid conflicts between modules with the same name.

Physically, a package is a folder, but there must be an _ _init _ _.py file in each folder. You may not write code in this file, or you may write code according to your needs. The written code will be imported in the package automatically executed. In related development tools, such as IDEA, after installing the Python plug-in, you can right-click to create a Python Package in the project, and an _ _init _ _.py file will be automatically generated after creation.

insert image description here

Create a settings package:
insert image description here

After the package is created, related modules can be created under this package for storage. There are usually three ways to import the imported modules for use:

(1) Load the specified module in the form of "import+full package name+module name"

Example: Create a size module and define two variables width and height

import settings.size
if __name__ == '__main__':
  print('宽度:',settings.size.width)    #在调用变量时需添加settings.size前缀
  print('高度:',settings.size.height)    #在调用变量时需添加settings.size前缀

(2) Load the specified module in the form of "from+full package name+import+module name"

Example:

from settings import size

if __name__ == '__main__':
    print('宽度:',size.width)    #在调用变量时需添加size前缀
    print('高度:',size.height)    #在调用变量时需添加size前缀

(3) Load the specified module in the form of "from+full package name+module name+import+definition name"

Example:

#导入包中的模块 (3)
from settings.size import width,height

if __name__ == '__main__':
    print('宽度:',width)    #在调用变量时无需添加前缀
    print('高度:',height)   #在调用变量时无需添加前缀

2.6 Referencing other modules

1. Import and use standard modules

Python has many built-in standard modules for us to use, which can be used directly by importing:

Example:

#导入标准模块库
import random

print(random.randint(0,10))   #输出一个0-10之间的随机整数

The standard libraries commonly used in python are as follows:
insert image description here

2. Download and installation of third-party modules

In addition to the built-in standard modules, there are many rich third-party modules for us to use, but they must be downloaded and installed before they can be used. Most of these can be found at http://pypi.org. We generally use pip for online installation, or offline installation as needed.

pip command modules
* command:用于指定要执行的命令。常用的有 install、uninstall、list等
* modulename:模块名

Example:

pip install numpy
pip list #查看己安装的模块

The learning about modules in Python is here today. In the later project development, we will often use it, and we will talk about it when the time comes.

Guess you like

Origin blog.csdn.net/whirlwind526/article/details/132402820
Recommended