"Learning Python with You Hand in Hand" 30-Module

In the previous article "Learning Python with You Hand in Hand" 29-Anonymous Functions , we introduced the format and usage of anonymous functions.

One of the advantages of using functions is that the code blocks of custom functions can be separated from the main program, making the entire code structure clearer and more readable. At the same time, the use of custom functions can also realize the reuse of code segments, avoiding the repeated occurrence of code segments that achieve the same effect in the entire program.

But the functions we learned before are all embodied in a program or file. Although they can be reused, they can only be reused in this program or file. If you want to reuse the same function in multiple programs or files, it is impossible to implement in the method we present.

Today we will introduce a method to store functions in separate files. By importing, you can reuse the same function in different programs or files without having to write the same function repeatedly in each program or file. Code.

This method is-module.

A module is an independent file that stores functions. Use the import statement to use the code in the module in the currently running program.

1. The meaning and value of the module

By storing the function in a separate file, we can focus on the higher-level code logic without considering the implementation process of the function. It not only allows us to reuse custom functions written by ourselves, but also allows us to share these modules (or functions) with other programmers, and even allows us to use other more advanced function libraries.

In the first article of this series- "Learning Python with You Hand in Hand" 1-Why learn Python? In, we introduced that libraries are one of the most unique features of Python.

In Python, there are not only many built-in libraries officially provided, but also many third-party libraries developed by external developers for Python. With the blessing of these "libraries", many complex and powerful functions do not need to be programmed by us users. As long as you call these libraries in Python, you can easily implement many powerful functions, such as graphics processing, natural language analysis, web crawlers, machine learning, and so on.

The library mentioned here refers to a function library, a large module composed of multiple functions. The process of calling these libraries is the process of importing modules using the import statement we are going to talk about today.

So, although today's content is very simple to learn and understand, it is the link that connects us Python beginners to the entire powerful Python world. With the blessing of these libraries, as long as we can master some basic Python statements and structures, we can achieve many powerful functions, which is very unimaginable for other programming languages.

Like Numpy and Pandas, which we will learn in the next stage, are the two most basic and important libraries in the field of data analysis. By importing and using Numpy and Pandas, we can not only master the method of data analysis using Python, but also surpass Excel and become the god of data analysis!

So, let us work hard together! ! !

2. Create a module

To make the function importable, you must first create a module.

A module is a file with a .py extension and contains the code to be imported into the program.

Since the file extension of Jupyter Notebook is .ipynb, it cannot be saved and imported as a module. Therefore, when making a module file, we need to use PyCharm software to write code and save the module. When importing the module for use, you can use Jupyter Notebook or PyCharm at will.

Let us create a module that contains two functions buy_iphone() and buy_ipad together:

In [1]: def buy_iphone(amount, model, *others):   # 使用了不定长函数
            print("\n购买{}台{},型号及颜色等要求如下:".format(amount, model))
            for other in others:
                print("- {}".format(other))
        def buy_ipad(amount, model, *others):
            print("\n购买{}台{},型号及颜色等要求如下:".format(amount, model))
            for other in others:
                print("- {}".format(other))

Save this code snippet in PyCharm as apple.py (the default is to save it as .py). This is the first module we created, which contains functions that we can import multiple times in a while.

3. How to import modules

There are many ways to import modules, and each method will be introduced one by one below.

a. Import the entire module

In the directory where apple.py is located, create a file named shopping_a.py. (If you create it with Jupyter Notebook, the file name is shopping_a.ipynb, it's all right.)

Use the import statement to import the module you just created, and you can call the functions inside.

In [2]: import apple
        apple.buy_iphone("1", "ihone 12", "型号:Pro Max", "颜色:蓝色", "内存:128GB", "1年延保服务")
        apple.buy_ipad("2", "iPad", "型号:Air4", "网络:WIFI", "颜色:绿色", "内存:256GB", "1年延保服务")

When running this code, import apple tells Python to open the apple.py file and copy all the functions in it to the current program, thus achieving the purpose of calling functions from other files or modules. The syntax format is:

import module name

We don't need to understand how the process of copying and calling is implemented. We only need to know that all the functions defined in apple.py can be used in the code of the shopping_a.py file.

To call a specific function in the imported module, you need to connect the name of the imported module and the name of the function to be used with an English period ".". The syntax format is:

Module name. Function name()

This grammatical format is very similar to the "object.method()" we introduced. It is also a manifestation of the ease of writing and high readability of Python programs.

In the above code, apple.buy_iphone() and apple.buy_ipad() are the process of calling two functions in apple.py.

Run the above program, you can get the following results:

Out[2]: 
        购买1台ihone 12,型号及颜色等要求如下:
        - 型号:Pro Max
        - 颜色:蓝色
        - 内存:128GB
        - 1年延保服务
        
        购买2台iPad,型号及颜色等要求如下:
        - 型号:Air4
        - 网络:WIFI
        - 颜色:绿色
        - 内存:256GB
        - 1年延保服务

In order to make the output beautiful, we have added the escape character "\n" in the function of the module, so there is a blank line before the output result. Since the output results are similar, the output results will not be shown in the following examples. You can run the program to view the input results.

This is the first method of importing a module. You only need to write an import statement and specify the module in it, and you can use all the functions in the module in the program.

b. Import specific functions

In addition to importing the entire module, you can also import specific functions in the module. The syntax format of this import method is:

from module name import function name

If you use a comma "," to separate the function names, you can also import any number of functions from the module as needed. The syntax format is:

from module name import function name 1, function name 2, function name n

For the apple.py module we created before, if you only want to import the buy_iphone() function, you can create another file shopping_b.py and write the following code:

In [3]: from apple import buy_iphone
        buy_iphone("1", "ihone 12", "型号:Pro Max", "颜色:蓝色", "内存:128GB", "1年延保服务")

It can be seen that when using this method, there is no need to use the syntax format of "module name.function name()", but just like ordinary custom functions, just use the function name to call the function directly.

c. Use as to assign aliases to functions

Since the function name of the module to be imported is already defined or universal, it may not be satisfied with the naming rules of one of our programs, and it may conflict with the function names in our existing programs. At this point, you can use the as keyword to name the functions we call from other modules, which is equivalent to a "nickname", and the syntax format is:

from module name import function name as alias

If you want to import multiple functions and rename them, you can write:

from module name import function name 1 as alias 1, function name 2 as alias 2, function name n as alias n

For the previously created module, we can create another file shopping_c.py to implement this import function:

In [4]: from apple import buy_iphone as ph, buy_ipad as pd
        ph("1", "ihone 12", "型号:Pro Max", "颜色:蓝色", "内存:128GB", "1年延保服务")
        pd("2", "iPad", "型号:Air4", "网络:WIFI", "颜色:绿色", "内存:256GB", "1年延保服务")

We can see that by renaming (aliasing) the function, not only the problem of reasonable naming can be solved, but the name of the function can also be simplified for ease of use. Of course, simplification should be done without affecting readability. \

d. Use as to assign an alias to the module

In addition to assigning aliases to functions, you can also assign simplified aliases to modules, so that we can use them when importing the entire module and calling functions. The syntax format is:

import function name as alias

When we use this import method, we can use the following code in shopping_d.py:

In [5]: import apple as a
        a.buy_iphone("1", "ihone 12", "型号:Pro Max", "颜色:蓝色", "内存:128GB", "1年延保服务")
        a.buy_ipad("2", "iPad", "型号:Air4", "网络:WIFI", "颜色:绿色", "内存:256GB", "1年延保服务")

The method of importing modules and calling functions is the same as the first method introduced, except that the simplified module name a replaces the original module name apple.

Because there are far fewer modules imported in a program than there are functions, it is generally used to simplify the module name instead of simplifying the function name to write the code. This achieves the purpose of simplifying the code, but also Will affect the readability of the program.

Therefore, this import method is also the most commonly used import method in Python, including our data analysis, we will often use:

import numpy as np

import pandas as pd

Such an import statement.

And function call statements such as np.array() and pd.DataFrame().

e. Import all functions in the module

Use "*" to import all functions in the module, and then you can use them like custom functions. The syntax format is:

from module name import *

Finally, create a shopping_e.py file and write the following code:

In [6]: from apple import *
        buy_iphone("1", "ihone 12", "型号:Pro Max", "颜色:蓝色", "内存:128GB", "1年延保服务")
        buy_ipad("2", "iPad", "型号:Air4", "网络:WIFI", "颜色:绿色", "内存:256GB", "1年延保服务")

Since all the functions in the module are imported, each function can be called directly by name in the program, instead of using "." to introduce it.

However, when we want to use modules that are not written by ourselves, especially large modules, it is best not to use this import method. Because the module to be imported may include a large number of functions that we do not confirm, its names may conflict with the names of functions in our current program. When encountering such repeated function names, Python will overwrite some of the functions instead of importing all functions separately, which may lead to some unexpected results.

Therefore, the best way is to import the entire module, and call and use the function through the combination of module name and function name. Of course, if necessary, you can also specify the module name to simplify the code.

The above is an introduction to the method of calling functions in other files by importing modules. At the same time, we also understand the calling principle of the powerful function library in Python, which lays the foundation for us to learn data analysis and other Python applications later.

In the next article, we will go a step further on the basis of calling functions, and take a look at how to directly read and write other files through Python, so stay tuned.

 

 


Thanks for reading this article! If you have any questions, please leave a message and discuss together ^_^

To read other articles in the "Learning Python with You Hand in Hand" series, please follow the official account and click on the menu selection, or click the link below to go directly.

"Learning Python with You Hand in Hand" 1-Why learn Python?

"Learning Python with you hand in hand" 2-Python installation

"Learning Python with You Hand in Hand" 3-PyCharm installation and configuration

"Learning Python with You Hand in Hand" 4-Hello World!

"Learning Python with You Hand in Hand" 5-Jupyter Notebook

"Learning Python with You Hand in Hand" 6-String Identification

"Learning Python with You Hand in Hand" 7-Index of Strings

"Learning Python with You Hand in Hand" 8-String Slicing

"Learning Python with You Hand in Hand" 9-String Operations

"Learning Python with You Hand in Hand" 10-String Functions

"Learning Python with You Hand in Hand" 11-Formatted Output of Strings

"Learning Python with You Hand in Hand" 12-Numbers

"Learning Python with You Hand in Hand" 13-Operation

"Learning Python with You Hand in Hand" 14-Interactive Input

"Learning Python with You Hand in Hand" 15-judgment statement if

"Learning Python with You Hand in Hand" 16-loop statement while

"Learning Python with You Hand in Hand" 17-the end of the loop

"Learning Python with You Hand in Hand" 18-loop statement for

"Learning Python with You Hand in Hand" 19-Summary of the first stage

"Learning Python with You Hand in Hand" 20-List

"Learning Python with You Hand in Hand" 21-Tuples

"Learning Python with You Hand in Hand" 22-Dictionary

"Learning Python with You Hand in Hand" 23-Built-in Sequence Function

"Learning Python with You Hand in Hand" 24-Collection

"Learning Python with You Hand in Hand" 25-List Comprehension

"Learning Python with You Hand in Hand" 26-Custom Functions

"Learning Python with You Hand in Hand" 27-Parameters of Custom Functions

"Learning Python with You Hand in Hand" 28-the return value of a custom function

"Learning Python with You Hand in Hand" 29-Anonymous Functions 

For Fans: Follow the "also said Python" public account and reply to "Hand 30" to download the sample sentences used in this article for free.

Also talk about Python-a learning and sharing area for Python lovers

 

Guess you like

Origin blog.csdn.net/mnpy2019/article/details/111068905