Home > Backend Development > Python Tutorial > What are anonymous functions in python? Grammar and example analysis

What are anonymous functions in python? Grammar and example analysis

乌拉乌拉~
Release: 2018-08-15 13:51:54
Original
2351 people have browsed it

In today’s article, we will learn about the python anonymous function in python functions. Many people don’t understand what anonymous function means. Today’s article will explain it. Friends, let’s understand what an anonymous function is. Without further ado, let’s start learning about anonymous functions.

Anonymous functions:

Python uses lambda to create anonymous functions.

lambda is just an expression, and the function body is much simpler than def.

The body of lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions.

lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace.

Although the lambda function seems to be able to write only one line, it is not equivalent to the inline function of C or C. The purpose of the latter is to call a small function without occupying stack memory and thereby increase the operating efficiency

Its syntax is as follows:

The syntax of lambda function only contains one statement, as shown in the figure below:

lambda [arg1 [,arg2,.....argn]]:expression
Copy after login

The example is as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 可写函数说明
sum = lambda arg1, arg2: arg1 + arg2;
 
# 调用sum函数
print "相加后的值为 : ", sum( 10, 20 )
print "相加后的值为 : ", sum( 20, 20 )
Copy after login

The above example Output result:

相加后的值为 :  30
相加后的值为 :  40
Copy after login

The above is what I want to explain today, the syntax of anonymous functions and an example. Although there are examples, hands-on practice is the best way to verify what you have learned. Finally, I hope this article can bring some help to you who are learning python.

For more related knowledge, please visit the Python tutorial column on the php Chinese website.

The above is the detailed content of What are anonymous functions in python? Grammar and example analysis. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template