Chapter VI Common module (1): What is the importing module, module and custom module

6.1 What is a module

What is a module? Module is a simple programming language understood point kit (bag with various methods available, functions, etc.), we can use the import module methods and functions of these modules.

In computer program development process, with more to write more program code in a file in the code will become longer and more difficult to maintain. In order to write code maintainable, we put a lot of function groups, which are placed in a separate file, so each file contains the code is relatively small, many programming languages ​​have adopted this way of organizing code. In python, a minimum .py file can be called a module (Module1), may be a directory (directory).

  • Benefits module: + improve code maintainability
    • Reusable. You can call the existing module when writing code (this can save a lot of code amount)
    • Function names and variable names to avoid conflicts (each module has a separate namespace)
  • Classification module: + standard module (built-in modules, the standard library): python comes, there are about 300.
    • Third-party modules: python community program ape who wrote the module, there are about 180,000. It needs its own installation (pip)
    • Custom modules: write your own. Python can be uploaded to the community.

help('modules') # 可以查询所有的本地模块,包括自己安装的 Module underlined are local calls

6.2 import module and custom module

6.2.1 Import & call function

  • Import function features:
    • Where a plurality of program modules may be introduced at the same time
    • When introduced into the same module is repeated, only the first identification

Import function has the following syntax:

import module_name  # 导入名字为module_name的整个模块

from module_name import child_m1,child_m2  # 从名字为module_name的模块中的导入其子模块child_m1和child_m2

from module_name.xx.xx import child_m1  # 导入子模块中的模块用'.'

from module_name import child_m1 as m_1  # 给导入的模块起个别名m_1,以后使用的时候可以用别名调用

from module_name.xx.xx improt *  # 导入模块中的所有子模块不推荐使用!
# 因为导入的模块里有很多方法时,有可能会被程序中定义的同名的方法覆盖,而且不易排查。
  • note:
    • Once the module is introduced into the (import), equivalent to the module performing the document py's code.
    • When python import module module file to find where?
      • Search module system can be confirmed with the following code paths
      import sys
      sys.path  # 显示搜索模块的路径列表,依次搜索,找到就读取并停止继续搜索,没找到就报错。
      # 这个列表可以添加,不过退出程序后不会保存对列表的修改。

      The results of windows:
      ['C:\\Users\\xxx\\Desktop\\python\\temp', 'C:\\Users\\xxx\\Desktop\\python', 'C:\\Program Files\\JetBrains\\PyCharm 2019.1.3\\helpers\\pycharm_display', 'C:\\Python37\\python37.zip', 'C:\\Python37\\DLLs', 'C:\\Python37\\lib', 'C:\\Python37', 'C:\\Users\\xxx\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\Python37\\lib\\site-packages', 'C:\\Program Files\\JetBrains\\PyCharm 2019.1.3\\helpers\\pycharm_matplotlib_backend']

      Common module is generally stored in the 'site-packages' directory

6.2.2 custom module

In python, once introduced into the module (Import), equivalent to the module performing the document py's code. > Import modules: the imported modules (introduction point of time) content is loaded into memory.

So, in a custom module in only defined function, you do not need to write to execute a statement. Because writing is executed at the time of import.

Here we use two examples to explain the custom module wording:

Example import executed (Error Example):

# 模块文件:module_test.py
def test_method():
    print('this is a test!')
    
test_method()
# import模块
import module_test  # 只是导入就会执行 module_test.py

Results of the:

this is a test!

Example typically custom module (Example right):

# 模块文件:module_test.py
def test_method():
    print('this is a test!')
# import模块
import module_test  # 只是导入就会执行 module_test.py
module_test.test_method()

Results of the:

this is a test!

6.2.3 Common Module - Module Kaiyuan

In order to facilitate the engineers of the world's total own custom module, python official of such a site.
URL is: https://pypi.python.org/pypi register an account you can upload your own modules of. You can also download some learning.

Installation module, the default is generally stored in the 'site-packages' directory, the file extension is .egg

  • There are two installation methods:
    • Manual installation, download the file to a local, with a build, install commands manually.
    • Online install (or uninstall), a pip (pip3) command to install

6.2.4 follicles (Package)

As more and more of your module file, you need to divide the module file. For example, the responsible interaction with the database are placed in a folder, a folder to put the lunar surface to interact with the relevant.

·
└── my_proj
    ├── crm  # 代码目录。
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── models.py
    │   ├── tests.py
    │   └── views.py
    ├── manage.py  # 入口程序。 -> 入口程序需要包同一级别才能导入
    └── proj  # 配置文件目录。
        ├── __init__.py
        ├── settings.py
        ├── urls.py
        └── wsqi.py

Such the upper and proj crm, a plurality of folder management module files, initialization files and folders __init__.py package is called.

init can write some initialization code within .py. It will be executed when importing package. (Usually empty file)
python3 folder can directly import
an empty file python2 directory must contain the name of the __init__.py (package initialization file) to import.

1. introducing a cross module

How module between packages import it? We need an entry program (in the example above manage.py) to import module (official recommended)

manage.py:

from crm import views

views.py:

from my_proj import settings

Because it is executed from the command interface program. So search path includes the directory manage.py, views.py import from here will start the search.

When we want to import the module views.py under other packages can do?

from my_proj import settings

As long as the program is executed by the entrance, no problem. Because before we talked about the search path sys.path to confirm the list of packages, the first search path is the path list of executable file (here we do is manage.py) of the current path.

2. Cross imported modules 2

When we want to directly execute views.py modules within other packages can also be invoked, we can manually append a path to sys.path list.

Note: Append path when you want to use relative paths. Otherwise, the execution environment change will fail

How to obtain the current path python do? 1. __file__ variable sys module holds the executable file on a relative path to the execution path.

  1. With os module os.path.abspath ( File ) to get the current absolute path.
  2. Then () method to obtain the name of the parent directory with the os module os.path.dirname.

Code Example views.py:

import sys
import os

BASE_DIR = os.path.dirname(os.path.dirname(sys.path.abspath(__file__)))  # 需要向上返回2级才能看到包

sys.path.append(BASE_DIR)  # 把路径添加到sys.path中。这个添加只在当次代码块执行中有效,执行结束后会重置列表。

from proj import settings  # 然后在下面面导入想到如的模块

So that we can also be imported directly executed views.py other package

3. Relative Import

We can use a relative path symbols '.' Import module

  • However, the use of relatively introduced with the following two conditions:
    • Folder must have a __init__.py file, which can be empty, but it must exist. ( The init .py is to allow the interpreter to identify the directory package initialization file)
    • Can not be performed as the top module py files in the folder (i.e. .. path after, the program can not be located in the directory entry: root directory)

For example views.py above example, we can have the following wording.

Code Example views.py:

from . import models  # 调用当前目录的models模块
from .. import settings  # ..回到了顶层目录,所以会报错

Guess you like

Origin www.cnblogs.com/py-xiaoqiang/p/11110845.html