Introduction to Python (17) Functions (5)

1. Storing functions in modules

One of the advantages of using functions is that you can separate blocks of code from the main program. By giving the function a descriptive name, the main program is made much easier to understand. You can go a step further and store functions in separate files called modules, and then import the modules into the main program. The import statement allows code from a module to be used in the currently running program file.

By storing functions in separate files, the details of the program code can be hidden, focusing on the high-level logic of the program. This also allows us to reuse functions in many different programs. By storing functions in separate files, these files can be shared with other programmers rather than the entire program. Knowing how to import functions also allows you to use libraries of functions written by other programmers.

There are many ways to import modules, each of which is briefly introduced below.

1.1 Import the entire module

To make a function importable, a module must first be created. Modules are files with a .py extension that contain code to be imported into a program. Let's create a module containing the function make_pizza(). To do this, delete other codes in pizza.py except the function make_pizza():

def make_pizza(size, *toppings):
    """概述要制作的比萨。"""
    print(f"\nMaking a {
      
      size}-inch pizza with the following toppings:")
    for topping in toppings:
        print(f"- {
      
      topping}")

Next, create a file called making_pizzas.py in the same directory as pizza.py. This file imports the module we just created, and calls make_pizza() twice:

  import pizza

  pizza.make_pizza(16, 'pepperoni')
  pizza.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

When Python reads this file, the line import pizza tells Python to open the file pizza.py and copy all the functions in it into the program. You can't see the copied code because Python is copying the code behind the scenes when the program is about to run. All you need to know is that in making_pizzas.py you can use all the functions defined in pizza.py.

To call a function in the imported module, specify the imported module's name pizza and the function name make_pizza(), separated by a period. The output of these codes is the same as the original program without importing the module:

Making a 16-inch pizza with the following toppings:
- pepperoni

Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
- extra cheese

This is one way of importing: just write an import statement and specify the module name in it, and all the functions in that module can be used in the program. If you imported the entire module named module_name.py using this import statement, you can use any of these functions using the following syntax:

module_name.function_name()

1.2 Import specific functions

You can also import specific functions in a module. The syntax for this import method is as follows:

from module_name import function_name

You can import as many functions as you want from a module by separating the function names with commas:

from module_name import function_0, function_1, function_2

For the previous making_pizzas.py example, if you only want to import the functions you want to use, the code will look like this:

from pizza import make_pizza

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

When using this syntax, the period is not required when calling the function. Since the function make_pizza() is explicitly imported in the import statement, it only needs to specify its name when calling.

1.3 Use as to assign an alias to the function

If the name of a function to be imported might conflict with an existing name in the program, or if the name of the function is too long, you can specify a short but unique alias: another name for the function, similar to a nickname. To give a function this special nickname, it needs to be specified when importing it.

The function make_pizza() is given the alias mp() below. This is achieved using make_pizza as mp in the import statement, the keyword as renames the function to the specified alias:

from pizza import make_pizza as mp

mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')

The import statement above renames the function make_pizza() to mp(). In this program, whenever make_pizza() needs to be called, it can be abbreviated as mp(). Python will run the code in make_pizza() to avoid confusion with the function make_pizza() that this program may contain.

The general syntax for specifying an alias is as follows:

from module_name import function_name as fn

1.4 Use as to assign an alias to the module

You can also specify an alias for a module. By assigning a short alias to the module (such as assigning the alias p to the module pizza), you can more easily call functions in the module. Compared to pizza.make_pizza(), p.make_pizza() is more concise:

import pizza as p

p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

The above import statement assigns the alias p to the module pizza, but the names of all functions in the module remain unchanged. To call the function make_pizza(), write the code p.make_pizza() instead of pizza.make_pizza(). This not only makes the code more concise, but also allows you to stop paying attention to the module name and only focus on the descriptive function name. These function names clearly indicate what the function does, and are more important to understanding the code than the module name.

The general syntax for assigning an alias to a module is as follows:

import module_name as mn

1.5 Import all functions in the module

Use the asterisk (*) operator to have Python import all functions in a module:

from pizza import *

make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

The asterisk in the import statement tells Python to copy every function in the module pizza into this program file. Since each function is imported, it can be called by name without using period notation. However, it is best not to use this method of importing when using large modules that you did not write yourself. This is because if there are functions in the module with the same name as those used in the current project, it may lead to unexpected results: Python may encounter multiple functions or variables with the same name, thereby overwriting functions, instead of importing all functions separately .

The best practice is to either import only the functions you need to use, or import the entire module and use period notation. This makes the code cleaner and easier to read and understand. The reason why this import method is introduced here is just to let you understand the import statement similar to the following when reading code written by others:

from module_name import *

2. Function Writing Guide

When writing functions, there are a few details to keep in mind. Functions should be given descriptive names, using only lowercase letters and underscores. A descriptive name helps you and others understand what the code is trying to do. The above conventions should also be followed when naming modules.

Each function should contain a comment briefly explaining what it does. The comment should immediately follow the function definition, in docstring format. A well-documented function allows other programmers to use it simply by reading the description in the docstring. They can trust that the code works as described, and they can use it in their programs as long as they know the name of the function, the required arguments, and the type of the return value.

When specifying default values ​​for formal parameters, do not have spaces around the equals sign:

def function_name(parameter_0, parameter_1='default value')

This convention should also be followed for keyword arguments in function calls:

function_name(value_0, parameter_1='value')

PEP 8 recommends that lines of code be no longer than 79 characters, so that as long as the editor window is modest, the entire line of code can be seen. If there are many formal parameters and the length of the function definition exceeds 79 characters, you can enter the left parenthesis in the function definition and press the Enter key, and press the Tab key twice on the next line, so as to indent the formal parameter list and only one level The function body is separated.

If your program or module contains multiple functions, you can use two blank lines to separate adjacent functions. This will make it easier to know where the previous function ends and the next function begins.

All import statements should be placed at the beginning of the file. The only exception is when a comment is used at the beginning of the file to describe the entire program.

Guess you like

Origin blog.csdn.net/qq_41600018/article/details/131152203