Getting started with Python(8)

Section 8****Module
Hello everyone, in the last lesson, we learned the functions of python. From this we know that Python programming can not only be achieved through some basic objects (such as constants and variables, operators and expressions) and flow control statements. Some simple applications can also build more complex program structures by creating functions.

Of course, we have learned to embed functions into the general program flow, even if it can solve some relatively complex problems, and even realize simple code reuse.

However, compared with other high-level languages, this is still far from enough. If we stop here, when we face a large and complex application requirement, it is difficult for us to use one or several applications to handle it. So, are there any more advanced tools for Python? It is as magical as Python, of course.

Tools that are more advanced than functions should have the following two properties:

(1) Its structure should be higher, which means it should be able to help us build an application system architecture.

(2) It allows us to conveniently call the encapsulated functions from anywhere in the system, maximizing the reuse of code blocks.

All so-called wisdom is ultimately to reduce the increase in entropy.

Achieving these two items will not only reduce the programmer's repetitive work, but more importantly, reduce the complexity of the system. This so-called "advanced tool" is the Python module we are going to introduce to you today.

**Pyhton module (Modules) is the highest level program organization unit of Python, which can encapsulate program code and data for reuse. **

Essentially, every python file is a python module. Moreover, after a module has imported other modules, it can directly use the variables and functions defined by the imported module.

So, it looks like nothing new!

PS: Yes, Watson has never been disdainful after Sherlock Holmes said the answer.

Basically, as long as we learn how to import modules, we can easily apply the concept of modules.

There are usually two ways to import modules:

1、 import statement

2、 from ... import statement

Just like many other excellent object-oriented programming languages, Python has also introduced this higher-level important object, which can integrate some reusable functions together to form a Python file. Then, it can be imported by any program and use any one of the functions.

This architecture greatly improves our programming efficiency. As a result, an important programming concept is also introduced, that is, when we encounter a need to construct any method (solution) to solve a problem, we must strive to "encapsulate" it in a reusable function. In this way, we have the opportunity to reuse code the next time we encounter the same or similar problems. **This is a very important programming idea.

1、 import statement

First, we create an empty module file: module_1.py, and add the following code.

Example module_1.py

def func_sun(x):

if x==1:

print('The rising sun on the grassland!')

else:

print('The sun is down, happy!')

**Description: **This module file contains a function, which has a formal parameter x, and determines what it displays to the screen according to whether the value received by the parameter is equal to 1.

Create another python application: module_app_1.py (in fact, it is still a python file, you can also use it as a module file if necessary)

Example module_app_1.py

import modlue_1

a=1

modlue_1.func_sun(a)

**Explanation: **This python program imports the module file module_1 through the import statement, and calls its function func_sun(), and at the same time passes the value of an actual parameter a to the function.

OK, the application of the import statement looks like this, have you learned it?

2、 from ... import statement

Next, let's modify the module file module_1.py and the program file module_app_1.py

Example modified module_1.py

def func_sun(x):

if x==1:

print('The rising sun on the grassland!')

else:

print('The sun is down, happy!')

def func_month():

print('The moon represents my heart!')

**Note: **The module file package adds a new function, which allows us to see the meaning of a module file: it can be a collection of several reusable functions. In fact, the collection of functions can make the module more meaningful.

Example modified module_app_1.py

a=1

b=2

if a==b:

from modlue_1 import func_sun

func_sun(a)

else:

from module_1 import func_month

func_month()

**Note: **Actually, the key point is here: we use the from...import statement to directly import the function of the module file module_1, and then use it like a local function (in this application file).

**Warning: **Although python supports from...import statements, in order to avoid name conflicts in your program, and to make the program easier to read, we should still try to avoid using module files in this way and choose simple use The import statement is obviously better.

3、 Python's built-in modules

Just as python has many built-in variables and functions, python also has many built-in modules, such as os module, sys module, hashlib module, time & datetime module, etc. The encapsulation of these built-in modules provides great convenience for us to realize application development.

For example, the sys module contains the following built-in functions (part of)

sys.argv command line parameter list, the first element is the path of the program itself

sys.exit(n) exit the program, exit(0) when exiting normally

sys.version Get the version information of the Python interpreter

sys.maxint The largest Int value

sys.path returns the search path of the module, using the value of the PYTHONPATH environment variable during initialization

sys.platform returns the name of the operating system platform

4、 sys.path

Here, to remind us of an important problem when using python modules: the path of module files. If the path is not set correctly, we will not be able to use the module file and its internal variables and function resources normally.

For python built-in modules, it naturally knows how to find the location of the module, because we have already configured it when we download and install Python. However, if we customize the module, we must pay special attention to it. When importing the module, the python interpreter will search from the directory provided by the sys.path variable. If the corresponding module is found, the statements in the module will start to run and can be used by you.

PS: When we call sys.path, we will find that the first string of sys.path is empty. This empty string represents the current directory, which is also part of sys.path.

**The sys.path and PYTHONPATH environment variables are consistent. This means that you can directly import the modules in the current directory. Otherwise, you must place your module file in the directory listed in sys.path, and you can also add the directory path where your module file is located by modifying the PYTHONPATH environment variable. **

5、 dir function

Python's built-in dir() function can return a list of names defined by objects.

dir() accepts parameters. If the parameter is a module name, the function will return a list of the names of this specified module. If no parameters are provided, the function will return a list of the names of all modules in the current directory.

Give the attribute name in the sys module

dir()

['__ annotations__', 'builtins', 'doc', 'file', 'loader', 'name', 'package', 'spec', 'a', 'b', 'func_sun', 'i', 'sys']

package

After understanding the concepts of functions and modules, we seem to be eager to try and start showing our skills.

Wait a minute!

Although what we are learning right now is just an introductory course, you can indeed write many or even some complex applications so far. So, we should also start to realize that in the face of an application demand, how to organize the basic structure of this application project? Therefore, we need to understand the concept of packages.

A package is a convenient way to organize modules hierarchically. More specifically, it is a folder: it contains modules and a special init.py file. This special file is an identifier of the package, and it is usually an empty file with no content automatically created by the IDE when creating the package folder. However, a folder lacking this file cannot be called a package.

Therefore, a simple understanding is: ** A folder containing a init.py file is a package, which can clearly organize module files hierarchically. **

For example: you want to create a package named "ab", which also contains other sub-packages such as "a" and "b", and these sub-packages all contain modules such as "a1" and "b1".

Then, the structure of this package folder is as follows:

summary

In this section, we learned about Python modules. Like the understanding of functions, modules not only better solve the problem of our reuse of program code, modules are also an important organizational form of application architecture, which brings the organizational structure of our applications to another dimension. In fact, the standard library that comes with Python is such an important set of examples of packages and modules.

**Dear students, at this point, we have completed the first phase of learning tasks for the basic introductory knowledge of Python. Please try to use what you have learned to solve some daily needs. For example, there is a random string of numbers. How do we arrange them from small to large? Or, in the face of consecutive integers ranging from 1 to 10000, how to add them up and sum them up? Try it, maybe you can do it? **

Preview

In the next lesson, we will come into contact with a very important concept: data structure. It can be said that it is an important reason why python applications appear powerful, and it is also a very important building block that constitutes our python entry knowledge structure.

Recommended Posts

Getting started with Python(18)
Getting started with Python(9)
Getting started with Python(8)
Getting started with Python(4)
Getting started with Python (2)
Getting started with python-1
Getting started with Python(14)
Getting started with Python(7)
Getting started with Python(17)
Getting started with Python(15)
Getting started with Python(10)
Getting started with Python(11)
Getting started with Python(6)
Getting started with Python(3)
Getting started with Python(12)
Getting started with Python(5)
Getting started with Python (18+)
Getting started with Python(13)
Getting started with Python(16)
Getting started with Numpy in Python
Getting started with Ubuntu
Getting Started with Python-4: Classes and Objects
Getting started with python-2: functions and dictionaries
04. Conditional Statements for Getting Started with Python
Getting started python learning steps
How to get started quickly with Python
python requests.get with header
Play WeChat with Python
Web Scraping with Python
Implementing student management system with python
Centos6.7 comes with python upgrade to
Played with stocks and learned Python
Gray-level co-occurrence matrix (with python code)
Speed up Python code with Cython
Automatically generate data analysis report with Python
Create dynamic color QR code with Python
Python | Quickly test your Python code with Hypothesis
How to process excel table with python