Design and application of Python modules

A module is a concept that contains between 1 and N files, and if the files are Python code files (i.e..py files), each file can contain functions, classes, and so on.

When I work in the company, many projects are completed by collaborative development. There may be many engineers behind a project. For the convenience of development, functions or classes that each person is responsible for are encapsulated in a module as far as possible. Just think of it as the same for you at this point.

There are a lot of open source modules on the Internet. One of the biggest advantages of these modules is that they are free. In many cases, using these modules can greatly improve the coding efficiency, which is one of the reasons many people like Python.

Put functions into modules

Module learning process, not according to the grammar structure to learn, it is a kind of abstract knowledge, is a code design way. For example, put written correspondence courses into modules.

Def kung_pao_chicken(* 8 ingredients): """ print(" ") for item in a tin (10 ingredients). Def yu_shiang_shredded_pork(**args): def yu_shiang_shredded_pork(**args): For item in args.items(): print(item)Copy the code

The above contents declare two functions, of course, the function name you must praise, translation accurate meaningful.

Next, combine the above functions into a single module, create a new file stir_fry.py and copy the two functions into the new file.

The stir_fry.py file contains those two functions

Ok, done, a module has been created, and the stir_fry.py file is a module.

You must have a black question mark in your head right now. What? That’s it. Yes, that’s it. A low profile module is complete.

Now you can use this module for others to use. Once you become the big cheese, you can teach the newbies how to write modules.

Application function module

Import Import module

In another file, you can import a module by importing the module name, such as the stir_fry module you just created.

Make sure to create a new file with an arbitrary name but not the same as the module.

Import stir_fry # Note that the imported module cannot be underlined, so the file name of the module cannot be underlined.Copy the code

If you want to use functions in modules, just refer to the syntax below.

Module name. function name ()Copy the code

Call a function in the module with stir_fry.

Import stir_fry stir_fry. Kung_pao_chicken (" cucumber ", "carrot "," chicken breast ", "peanut ") stir_fry. Yu_shiang_shredded_pork (old=" ersatz fish fillet ", New =" No fish in big guy's fish-flavored pork ")Copy the code

When the module is imported with the import stir_fry, all functions in the module are imported into the new file at once.

Import a module function

If you don’t want to import all of a module’s functions, but import only one function, use the following syntax to solve this problem.

From module name import function nameCopy the code

Modify the case in the previous section:

From stir_fry import kung_pao_chicken kung_pao_chicken(" cucumber ", "carrot "," chicken breast ", "peanut ") Yu_shiang_shredded_pork (old=" eraser ", new=" big guy ")Copy the code

Import functions directly into a module without passing the module name. Write the function name directly.

Import multiple functions in a module

The syntax is as follows:

From module name import function name 1, function name 2...Copy the code

Import all functions of the module

The syntax is as follows:

From module name import *Copy the code

As an alias

You may have noticed a potential problem when importing functions from modules. In addition to long names, there is also the risk that the names of functions in modules are the same as those of functions in the current file. Here’s a new lesson to learn: give the functions imported by the module individual names via AS, and then encode them all in the file using aliases.

The syntax is as follows:

From module name import function name AS aliasCopy the code

The above applies to the case as follows:

Stir_fry import kung_pao_chicken as pao pao(" cucumber ", "carrot "," chicken breast ", "peanut ")Copy the code

As aliases can also be used directly on modules in the following syntax:

Import Module name AS aliasCopy the code

Put classes in modules

As programming becomes more and more complex, it is no longer enough to just put functions into modules. You need to put more advanced things into modules, namely classes.

Start by defining a class in the dog_module.py file.

Class Dog(): def __init__(self): self. Name = "self" def say(self): print(self)Copy the code

In this case, dog_module is the name of the module, and there is only one class Dog in the module. You can also create more classes in the module, for example:

Class Dog(): def __init__(self): self. Name = "" def say(self): print(" ") class Cat(): def __init__(self): Self. name = "def say(self): print(self)Copy the code

Import Import module (class)

As with the function part of importing a module, if you want to import a class from a module, you can do so directly with the following syntax:

The import module nameCopy the code

Using classes in modules, the syntax is as follows:

Module name. Class nameCopy the code

The specific code is not demo, do it yourself.

Import a module class

The use of classes for importing modules is consistent with the use of functions for importing modules.

Create a new demo.py file that imports the classes in the dog_module module.

From dog_module import Dog Dog = Dog() dog.say()Copy the code

Import multiple classes from a module

This method is the same as function import, and the syntax format is as follows:

Import class name 1, class name 2, class name 3...Copy the code

Import all classes in the module

From module name import *Copy the code

At this point, you should have noticed that the functions in an imported module and the classes in an imported module are almost indistinguishable from each other in terms of code writing.

You can also apply aliases when importing classes, again using the AS syntax.

The common module

Now that you have a basic understanding of what a module is and how to use it, instead of writing a special module, let’s apply some common modules.

Random number random module

A number can be obtained through the random number module, which can be used in a wide range of scenarios, such as game-related development, verification code related, lottery related. After learning the random number, you can complete some very good small cases.

Randint method

After importing the random number module, we can use the randint method to randomly generate an integer, as shown in the following code:

Num = random. Randint (1,10) print(num)Copy the code

Running the code repeatedly yields a number between 1 and 10, from which you can see the meaning of the argument in the randint method.

Randint (min, Max) # min min, Max MaxCopy the code

Could you try aliasing randint?

Method of choice

The choice method is used to implement some effects with the list, which returns a random element from the list.

Play = random. Choice ([" football ", "basketball "," table tennis ", "baseball "]) print(play)Copy the code

If you want to know exactly how to use the choice method, remember how to query?

Print (help(random. Choice))Copy the code

Shuffle method

This method can shuffle the order of a list.

My_list = [" football ", "basketball "," ping-pong ", "baseball "] random. Shuffle (my_list) print(my_list)Copy the code

Three methods in the Random module are simply selected as explanations. For module learning, a separate article will be written for each module.

Time module

The time module is a very important built-in module in Python. It is used in many scenarios. Built-in modules are modules that come with Python when it is installed.

The time module is mainly used to manipulate time. There is a time object in this method. After using the time method, you can obtain the number of seconds from 00:00:00 on January 1, 1970 to the present, which is called the timestamp in many places.

import time

print(time.time())
Copy the code

Output content:

1606810686.3747146
Copy the code

The sleep method pauses the program. The parameter is in seconds.

The syntax format is:

Import time time.sleep(10) # pause the program for 10 seconds before executingCopy the code

Asctime and localtime methods

Both methods can return the current system time, but in different forms.

import time

print(time.asctime())

print(time.localtime())
Copy the code

There are only so many methods involved in the Time module at first, which will be supplemented in the subsequent snowball learning process.

Python also has many built-in modules, such as sys module, OS module, JSON module, pickle module, shelve module, XML module, re module, logging module, and so on. We will learn more about these modules in the future.

Summary of this blog post

Python modules are a quick way to code. In many cases, third-party modules can help you solve most common coding scenarios and get you on the road to coding.