python learning, module

python module

What is a module

A module is a piece of Python code with a complete set of functions and a logical organization.

Modules are usually designed to make your code organization clear, hierarchical, and easier to maintain and read

Usually in python, a module is a python file

This file may define many functions, classes, variables, etc.

A simple module

A file api.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env python
#-*-coding: UTF-8-*-
# /***********************************************************************************
# Copyright: 2019-2020
# FileName: api.py
# Author: Hello, front club
# Version:
# Date Of Creation: 2019/09/21 13:03:00
# Description:
#:
#:
# Function List:
# ***********************************************************************************/

import json

name_str = "Hello, front club"


def get_name():
  "" "
    Get json string
  "" "
  name_dict = dict(name = name_str)
  return json.dumps(name_dict)


if __name__ == "__main__":
  pass

The above is a module api.py. Next we will import this module and use the functions provided by this module.

This module includes a function get_name()

Now let’s see how to use modules

main.py

1
2
3
4
from api import get_name

if __name__ == "__main__":
  get_name()

This place uses from import to import the module api.py we just wrote, which we call the api module

The function get_name was imported from the api module, so we can call this function

How to import modules

import

To use a module, you must import the module through import to use the functions in the module

1
2
3
import os

print(os.path)

The import os is to import the os module, so you can use the functions in os

Output after execution:

1
<module 'posixpath' from '/usr/lib64/python3.6/posixpath.py'>

from … import

1
from api import get_name

Import get_name from api module, so you can use get_name directly

Let’s take a look at the packages related to modules in the next section

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