python learning, package

Python package in detail

What is a bag

Packages are a way to manage modules, and they also define namespaces for modules

For example, there is a package called A, and there is a module called B, and the module to be accessed is A.B

The dots here indicate the attribute access, the module belongs to the package

For example, you developed a module called http.py, and others also developed a module called http.py. The same module,
Which one is quoted? Easy to mix dishes, so managed by package

The package you developed is called me, and there are many modules in it, including http.py
The package developed by others is called text, and there are many modules in it. When the hot includes http.py

To access your module, use me.http
To access someone else’s module, use text.htp

This accesses the module by qualifying the namespace

Python package structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
me /
|-audio
| |-__init__.py
| |-settings.py
| |-urls.py
| `-wsgi.py
|-video
| |-__init__.py
| |-name.py
| |-count.py
| `-req.py
|-settings.py
|-urls.py
`-wsgi.py

There are two packet structures above, one is audio and the other is video

Each package must have an init.py file
This file is very important. One is to identify that this is a python package. The other is that this file contains the code that controls the usage of the package.
When importing packages, each file in the directory is not immediately imported, init.py is calculated first

The simplest way of init.py is empty content

The package audio contains three modules, settings.py urls.py wsgi.py

The package video contains two modules, name.py count.py req.py

How to import packages

When importing a package, Python will look for the package based on the path in sys.path

Import a package

1
import os

Imported a package os

Import modules from package

1
from django import http

Indicates that the module http was imported from the package django

Import all modules in the package

1
from os import *

Import all modules in package os

However, this way of importing all modules is a very dangerous operation

Persist in original technology sharing, your support will encourage me to continue to create!