Detailed package

package

First, what is the package

The nature of the package module also can be understood as an internal module contains many modules, this is the package. In Python2, the next package must contain __init_ module package before they can become, but in Python3 in even without _ the init , will be the default for the package.

Second, import the package

2.1 Usage: 1%

At the outset, this case is primarily a designer bag made out to the user to use some features, like the time module, we do not know what is in the end its internal structure, only need to know that we import this module, using a special call You may use some of its internal functions.

Package is a module, what happened when we import the module can also occur when you import the package. But there is so little not the same.

  1. __init__ file to execute the package level
  2. Generating a namespace name for storing generated during execution __init__
  3. Init generates a name space that points to the current space in the package.

To understand, not directly import the package to package all been imported, but only executed _ init__ file and generate namespace init, _ init .py equivalent to the bag transfer station, provides the interface to the external caller to use. So some of the information imported modules in the package are stored in the init, the user only needs to import the package outside to call init on it.

While the inner init file in the package the bag is introduced into an additional import function may be used or from..import syntax.

In this way, users do not need to import other extra stuff, the designer in the design of the package when they are taken into account, attach it to the inside init.

Introducing two kinds of packets 2.2

There are two packages introduced:

  1. Absolute Import: Import the starting position of the other modules should start from the top-level package to write down.

  2. Relative import: import other modules starts from current module. A dot represents the current position. Two representatives return to the previous point.

In response to these structures, if I want to use internal or foo foo certain functions.

# 使用者的py文件内部的代码
import aaa  # 相当于执行了其下一级的__init__。

# init内部的代码可以用两种方式。
# 绝对导入
from aaa.bbb import foo
from aaa.bbb.foo import x

# 相对导入
from .bbb import foo
from .bbb.foo import x

To point to note:

  1. Introducing relative package internal use only, is the most suitable introducing method used in the package.
  2. from..import import or syntax, as long as a little of the left point must be a package.

2.2 Usage: 99%

Among the most case, packages are what we own to do the project, but also in the python3, without init package can also be used between different projects is mainly used in the previous section we talked about in module import.

Detailed Module: [ https://www.cnblogs.com/liqianxin/p/12584399.html ]

Guess you like

Origin www.cnblogs.com/liqianxin/p/12593669.html