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

In the previous articles, we fully introduced the features, parameters, and return values ​​of Python custom functions. You can learn about them by clicking the link below.

"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

Although custom functions are powerful, they are not all of Python.

Today, we are going to learn a new function called anonymous function. Anonymous function can also be regarded as a kind of custom function in essence, but it is displayed in an anonymous way.

1. The definition of anonymous functions

We know that every custom function has a function name and is declared by the def keyword. An anonymous function does not need to define a function name. It is defined through the Lambda keyword, telling everyone "I have no name, I am an anonymous function".

But this may just be the reason why Lambda functions are translated into "anonymous functions". In principle, the reason why anonymous functions are called "anonymous functions" is because -

Unlike the function declared by the def keyword, the anonymous function object itself does not have an explicit __name__ attribute.

Seeing this kind of explanation is a bit unclear, in fact, I don't understand it either. Just take it as a little bit of knowledge that we have learned in advance. As we continue to learn, we may understand it later. . .

2. The role of anonymous functions

An anonymous function is a way to generate a function through a single statement, and the result is the return value.

In [1]: def pingfang(x):
            return x * x
            
        result = pingfang(2)
        print(result)
        
Out[1]: 4
In [2]: result = lambda x: x * x
        print(result(2))
Out[2]: 4

From the comparison of the above two examples, we can see the following two points:

1. Anonymous function is a compact form of expression of custom function. It only needs one line of code to realize the function of the entire code segment from definition to return value of ordinary custom function, and it has higher readability. It is also a very commonly used writing form in Python programming.

But when applying anonymous functions, generally only some relatively simple functions are converted into anonymous functions for use. If it is a very complex and large function, it is still necessary to use the form of a custom function. If it is forced to be implemented as an anonymous function, it may not be worth the loss.

2. The lambda function returns the function name as the result. After applying the anonymous function, the variable result that originally received the return value of the function actually becomes a result(x) function, that is, we use the lambda keyword to define a result(x) function with one line of code. If we modify the variable name, this relationship may become clearer.

In [3]: pingfang = lambda x: x * x
        print(pingfang(2))
Out[3]: 4

3. The format of anonymous functions

From the above example, we have also seen that an anonymous function is a statement defined by the lambda keyword, and its syntax format is:

<function name> = lambda <parameter>: <expression>

It can also be seen from the syntax format, which is the same as what we said in the second point above. The lambda function returns a <function name>.

Although anonymous functions are generally used for the definition of relatively simple functions, the above examples have only one parameter, which is too simple. Here are a few more complicated but very efficient examples.

In [4]: tixingmianji = lambda shangdi, xiadi, gao: (shangdi + xiadi) * gao / 2   # 多个参数
        print("梯形面积等于{}。".format(tixingmianji(2, 5, 3)))
Out[4]: 梯形面积等于10.5。
In [5]: str = ['lee', 'jupyter', 'aaaaa', '23400', '**##^^']
        str.sort(key = lambda x: len(set(list(x))))   # 按照字符串不重复元素的个数排列,set()用于去除重复元素
        str
Out[5]: ['aaaaa', 'lee', '**##^^', '23400', 'jupyter']

 4. Currying

Currying is a computer science term (named after the mathematician Haskell Curry), which means that a new function is derived from an existing function through the application of some parameters.

For example, we have an unimportant function whose function is to add two numbers together:

def add_numbers(x, y):
    return x + y

Using this function, we can derive a new function with only one variable, add_five, that is, you can add 5 to the parameter:

add_five = lambda y: add_numbers(5 + y)

Among them, the second parameter y, for the function add_numbers, is currying.

Although the name sounds very big, the process is easy to understand. In fact, a new function (add_five) is defined using an anonymous function, and this new function calls an existing function (add_numbers).

The above is our explanation of anonymous functions.

But we found that up to now, the functions we have learned are all embodied in a program or file. Although it can be reused, it can only be reused in this program or file. If you want to reuse the same function in multiple programs or files, do you still need to define the same function in each program or file?

In the next article, the module we will introduce is to solve the method of reusing functions in different programs or files, 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

For Fans: Follow the "also said Python" public account, reply to "hand 29", you can 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/110679649