[Learning python from zero] 38. How to use and import Python packages

package use

A module is a py file. In order to classify and manage modules in Python, different folders need to be divided. Multiple related modules can be placed in the same folder. For the convenience of calling, a code folder in Python is generally called a package.

1. How to import packages

The following package newmsg is available. There are two modules in the package, namely sendmsg.py and recvmsg.py files. In the parent folder of the package, there is a test.py file, the goal is to introduce two modules of newmsg in the test.py file.

The directory structure is shown in the figure below:

- newmsg/
  - __init__.py
  - sendmsg.py
  - recvmsg.py
- test.py

The contents of the sendmsg.py file are as follows:

def send_msg():
  print('------sendmsg方法被调用了-------')

The contents of the recvmsg.py file are as follows:

def recv_msg():
  print('-----recvmsg方法被调用了--------')

There are several ways to import a module and use the methods in the module.

  1. Import the specified module directly using packagename.modulemodulename.
import newmsg.sendmsg
  1. Use from xxx import xxx to import the specified module.
from newmsg import sendmsg
  1. Use the __init__.py file to import the specified modules in the package.

You can create an __init__.py file in newmsg, and import the specified content in this file.

Write the code in the __init__.py file:

from . import sendmsg  # 导入指定的模块    . 代表的是当前文件夹

The code in the test.py file:

import newmsg
newmsg.sendmsg.send_msg()  # 可以直接调用对应的方法
# newmsg.recvmsg.recv_msg()   不可以使用 recvmsg 模块,因为 __init__.py文件里没有导入这个模块
  1. Use the __init__.py file, combined with the __all__ attribute, to import all modules in the package.

Write code in the __init__.py file in the newmsg package:

__all__ = ["sendmsg","recvmsg"]  # 指定导入的内容

test.py file code:

from newmsg import *  # 将newmsg里的__inint__.py文件里,__all__属性对应的所有模块都导入
sendmsg.send_msg()
recvmsg.recv_msg()

Summarize

The package organizes related modules together, that is, puts them in the same folder, and creates a file named __init__.py in this folder, then this folder is called a package, which effectively avoids the problem of module name conflicts , making the application organization structure clearer.

2. What is the use of the init.py file

init.py controls the import behavior of the package. The init.py is empty only to import this package, and will not import the modules in the package. Content can be written in the __init__.py file.

newmsg/ init.py file:

print('hello world')

When other modules import this package, they will automatically call this code.

3. all

In the __init__.py file, define a __all__ variable that controls the modules imported when from package name import *.

newmsg/ init.py file:

__all__ = ['sendmsg','recvmsg']

Precautions

When customizing modules, you need to pay attention to the fact that the custom module name should not be the same as the system module name, otherwise problems will occur!

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/132335864