[Learn python from zero] 34. Detailed explanation of the import and use of Python modules

Modules in Python

There is a concept in Python called a module.

To put it plainly: a module is like a toolkit. To use the tools (like functions) in this toolkit, you need to import this module

For example, we often use the tool random, which is a module. After using import randomthe import tool, the function of random can be used.

import module

1. There are five ways to import modules

  • import 模块名
  • from 模块名 import 功能名
  • from 模块名 import *
  • import 模块名 as 别名
  • from 模块名 import 功能名 as 别名

2. import

Use keywords to import a certain module in Python import. For example, to import a system module math, it can import mathbe used .

grammar:

import 模块1,模块2,...  # 导入方式

模块名.函数名()  # 使用模块里的函数

think about it:

Why must add the module name call?

answer:

Because there may be such a situation: there are functions with the same name in multiple modules. At this time, if it is only called by the function name, the interpreter cannot know which function to call. So if you import a module like the above, you must add the module name to the calling function

Example:

import math

#这样才能正确输出结果
print(math.sqrt(2))

#这样会报错
print(sqrt(2))

3. from…import

Sometimes we only need to use a certain function in the module, just need to import the function, at this time we can use the following method to achieve:

from 模块名 import 函数名1,函数名2....

Not only can you introduce functions, but you can also introduce some global variables, classes, etc.

Notice:

When importing in this way, only the function name can be given when calling the function, and the module name cannot be given. However, when two modules contain functions with the same name, the latter import will overwrite the previous import. That is to say, if there is a function in module A function(), there is also a function in module B. function()If the function in A is introduced functionfirst and the function in B is functionintroduced later, then when the function is called , the function functionin module B is executed .function

For example, to import a function fibof a module fibonacci, use the following statement:

from fib import fibonacci

Note: It will not fibimport the entire module into the current namespace, it will only import a single function fibinfibonacci

4. from … import *

It is also possible to import all the contents of a module into the current namespace, just use the following declaration:

from modname import *

NOTE: This provides an easy way to import all projects in a module. However, this statement should not be used too much.

5. asAlias

import time as tt  # 导入模块时设置别名为 tt

tt.sleep(1)  # 使用别名才能调用方法

from time import sleep as sp  # 导入方法时设置别名

sp(1)  # 使用别名才能调用方法

When a module is very long and we only need one of the functions, but the function name is relatively long or not intuitive enough, then we can use askeywords to set aliases for the functions to make the function calls more convenient and concise.

For example, if we import the module numpyand use it import numpy as np, then we can np.array()call the function numpyin the module by array.

in conclusion

  • When importing importthe entire module, you need to use 模块名.函数名()the method to call the function in the module.
  • Use from 模块名 import 函数名can directly use the function name to call the function in the module.
  • Use from 模块名 import *all functions in a module that can be imported, but are deprecated.
  • Use import 模块名 as 别名can set an alias for the module, use 别名.函数名()to call the function in the module.
  • You from 模块名 import 函数名 as 别名can set an alias for the function and use the alias to call the function.

These methods of importing modules can be selected according to actual needs, and flexible use can make our code clearer, more concise and easier to read.

Advanced case

[Python] Python realizes the word guessing game-challenge your intelligence and luck!

[python] Python tkinter library implements GUI program for weight unit converter

[python] Use Selenium to get (2023 Blog Star) entries

[python] Use Selenium and Chrome WebDriver to obtain article information in [Tencent Cloud Studio Practical Training Camp]

Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition

[Fun with Python series [Xiaobai must see] Python multi-threaded crawler: download pictures of emoticon package websites

[Play with Python series] [Must-see for Xiaobai] Use Python to crawl historical data of Shuangseqiu and analyze it visually

[Play with python series] [Must-see for Xiaobai] Use Python crawler technology to obtain proxy IP and save it to a file

[Must-see for Xiaobai] Python image synthesis example using PIL library to realize the synthesis of multiple images by ranks and columns

[Xiaobai must see] Python crawler actual combat downloads pictures of goddesses in batches and saves them locally

[Xiaobai must see] Python word cloud generator detailed analysis and code implementation

[Xiaobai must see] Python crawls an example of NBA player data

[Must-see for Xiaobai] Sample code for crawling and saving Himalayan audio using Python

[Must-see for Xiaobai] Technical realization of using Python to download League of Legends skin pictures in batches

[Xiaobai must see] Python crawler data processing and visualization

[Must-see for Xiaobai] Python crawler program to easily obtain hero skin pictures of King of Glory

[Must-see for Xiaobai] Use Python to generate a personalized list Word document

[Must-see for Xiaobai] Python crawler combat: get pictures from Onmyoji website and save them automatically

Xiaobai must-see series of library management system - sample code for login and registration functions

100 Cases of Xiaobai's Actual Combat: A Complete and Simple Shuangseqiu Lottery Winning Judgment Program, Suitable for Xiaobai Getting Started

Geospatial data processing and visualization using geopandas and shapely (.shp)

Use selenium to crawl Maoyan movie list data

Detailed explanation of the principle and implementation of image enhancement algorithm Retinex

Getting Started Guide to Crawlers (8): Write weather data crawler programs for visual analysis

Introductory Guide to Crawlers (7): Using Selenium and BeautifulSoup to Crawl Douban Movie Top250 Example Explanation [Reptile Xiaobai must watch]

Getting Started Guide to Crawlers (6): Anti-crawlers and advanced skills: IP proxy, User-Agent disguise, Cookie bypass login verification and verification code identification tools

Introductory Guide to Crawlers (5): Distributed Crawlers and Concurrency Control [Implementation methods to improve crawling efficiency and request rationality control]

Getting started with crawlers (4): The best way to crawl dynamic web pages using Selenium and API

Getting Started Guide to Crawlers (3): Python network requests and common anti-crawler strategies

Getting started with crawlers (2): How to use regular expressions for data extraction and processing

Getting started with reptiles (1): Learn the basics and skills of reptiles

Application of Deep Learning Model in Image Recognition: CIFAR-10 Dataset Practice and Accuracy Analysis

Python object-oriented programming basics and sample code

MySQL database operation guide: learn how to use Python to add, delete, modify and query operations

Python file operation guide: encoding, reading, writing and exception handling

Use Python and Selenium to automate crawling#【Dragon Boat Festival Special Call for Papers】Explore the ultimate technology, and the future will be due to you"Zong" #Contributed articles

Python multi-thread and multi-process tutorial: comprehensive analysis, code cases and optimization skills

Selenium Automation Toolset - Complete Guide and Tutorials

Python web crawler basics advanced to actual combat tutorial

Python introductory tutorial: master the basic knowledge of for loop, while loop, string operation, file reading and writing and exception handling

Pandas data processing and analysis tutorial: from basics to actual combat

Detailed explanation of commonly used data types and related operations in Python

[Latest in 2023] Detailed Explanation of Six Major Schemes to Improve Index of Classification Model

Introductory Python programming basics and advanced skills, web development, data analysis, and machine learning and artificial intelligence

Graph prediction results with 4 regression methods: Vector Regression, Random Forest Regression, Linear Regression, K-Nearest Neighbors Regression

Guess you like

Origin blog.csdn.net/qq_33681891/article/details/132334555
Recommended