简体   繁体   English

lambda 和常规 function 之间的 python 有什么区别?

[英]what is the difference for python between lambda and regular function?

I'm curious about the difference between lambda function and a regular function (defined with def ) - in the python level.我很好奇lambda function 和常规 function(用def定义)之间的区别 - 在 python 级别。 (I know what is the difference for programmers and when to use each one.) (我知道程序员有什么区别以及何时使用它们。)

>>> def a():
    return 1

>>> b = lambda: 1
>>> a
<function a at 0x0000000004036F98>
>>> b
<function <lambda> at 0x0000000004031588>

As we can see - python knows that b is a lambda function and a is a regular function. why is that?正如我们所见 - python知道b是一个lambda function 而a是一个普通的 function。这是为什么呢? what is the difference between them to python ?它们与 python有什么区别?

They are the same type so they are treated the same way:它们是相同的类型,因此它们的处理方式相同:

>>> type(a)
<type 'function'>
>>> type(b)
<type 'function'>

Python also knows that b was defined as a lambda function and it sets that as function name: Python 也知道b被定义为一个 lambda 函数并将其设置为函数名:

>>> a.func_name
'a'
>>> b.func_name
'<lambda>'

In other words, it influences the name that the function will get but as far as Python is concerned, both are functions which means they can be mostly used in the same way.换句话说,它会影响函数将获得的名称,但就 Python 而言,两者都是函数,这意味着它们主要可以以相同的方式使用。 See mgilson's comment below for an important difference between functions and lambda functions regarding pickling.有关酸洗的函数和 lambda 函数之间的重要区别,请参阅下面的 mgilson 评论。

The only difference is that (a) the body of a lambda can consist of only a single expression, the result of which is returned from the function created and (b) a lambda expression is an expression which evaluates to a function object, while a def statement has no value, and creates a function object and binds it to a name.唯一的区别是 (a) lambda 的主体只能由单个表达式组成,其结果从创建的函数返回; (b) lambda表达式是一个计算结果为函数对象的表达式,而 a def语句没有值,并创建一个函数对象并将其绑定到一个名称。

In all other material respects they result in identical objects - the same scope and capture rules apply.在所有其他物质方面,它们导致相同的对象 - 适用相同的范围和捕获规则。 (Immaterial differences are that lambda -created functions have a default func_name of "<lambda>" . This may affect operation in esoteric cases - eg attempts to pickle functions.). (无关紧要的区别是lambda创建的函数的默认func_name"<lambda>" 。这可能会影响深奥情况下的操作 - 例如尝试pickle 函数。)。

Both lambda and def create the same kind of function – they have the same kind of metadata and capabilities. lambdadef创建相同类型的 function——它们具有相同类型的元数据和功能。 Their technical difference is syntactical :它们的技术差异是语法上的:

  • A lambda is an expression producing a function. lambda是一个产生 function 的表达式
  • A def is a statement producing a function. def是生成 function 的语句

This is everything that dictates how they can be used .这是决定如何使用它们的一切。 Other apparent differences simply come from the information lambda / def can capture.其他明显的差异仅来自lambda / def可以捕获的信息。

>>> def def_func(): pass
>>> lambda_func = lambda: None
>>> type(def_func) == type(lambda_func)
True

Usage: Expression vs. Statement用法:表达式与语句

A lambda is more flexible as expressions can be part of more language constructs. lambda更灵活,因为表达式可以是更多语言结构的一部分

#                v--------------v arguments must be expressions
sort(values, key=lambda x: abs(x))

In contrast, a def is more powerful as it can consist of more language constructs.相反, def更强大,因为它可以包含更多的语言结构。

def encode(num, base):
    while num:   # statements must be inside statements
        num, bit = divmod(num, base)
        yield bit

These differences derive directly from one being an expression and the other being a statement.这些差异直接源于一个是表达式,另一个是语句。 Python has no special rules to decide where a lambda / def may be used. Python 没有特殊规则来决定在哪里可以使用lambda / def


Where the wild <lambda> s grow野生<lambda>生长的地方

The primary reason to assume lambda and def correspond to different kinds of function is metadata : lambda is often referred to as an "anonymous function" and miraculously it always produces a function <lambda> .假设lambdadef对应于不同种类的 function 的主要原因是元数据lambda通常被称为“匿名函数”并且奇迹般地它总是产生function <lambda> Other quirks include "lambda functions can't be pickled", and recently typing also does "not work" for lambda .其他怪癖包括“无法腌制 lambda 函数”,并且最近输入对于lambda也“不起作用”。

That is because compared to def syntax, the lambda syntax has no way of specifying name, type annotations and similar.这是因为与def语法相比, lambda语法无法指定名称、类型注释等。 As such, Python simply fills in sane defaults for either: the name becomes <lambda> and annotations are left empty.因此,Python 只是简单地为两者填写合理的默认值:名称变为<lambda>并且注释留空。

>>> identity = lambda a: a
>>> identity.__qualname__
'<lambda>'
>>> identity.__annotations__
{}

Since <lambda> is not a valid identifier, everything using this metadata to find the function – most prominently pickle – fails.由于<lambda>不是有效标识符,因此使用此元数据查找 function(最显着的是pickle )的所有操作都失败了。

However, that does not make the function an "anonymous function" type.但是,这并不会使 function 成为“匿名函数”类型。 The metadata can be patched up to insert what def would provide:可以修补元数据以插入def将提供的内容:

>>> identity.__qualname__ = identity.__name__ = 'identity'
>>> identity
<function __main__.identity(a)>

Of course at that one point one can just use def当然,在那一点上可以只使用def ……

lambda creates an anonymous function. lambda创建一个匿名函数。 This idea has been taken from functional programming languages.这个想法来自函数式编程语言。 In this way you can create and pass the function to other functions like map and filter .通过这种方式,您可以创建函数并将其传递给其他函数,例如mapfilter (look here ) (看这里
You can pass normal functions to these functions too, but since mostly they are simple and they are not used anywhere else, it's inconvenient to go through the whole process of definfing a new function.您也可以将普通函数传递给这些函数,但由于它们大多很简单并且不会在其他任何地方使用,因此不方便完成定义新函数的整个过程。

As an example take a look at this:作为一个例子,看看这个:

>>> a = [1, 2, 3, 4]
>>> print map( lambda x : x*2 + 1, a )
[3, 5, 7, 9, 11]

Lambda is an inline function where we can do any functionality without a function name. Lambda 是一个内联函数,我们可以在没有函数名称的情况下执行任何功能。 It is helpful when we use it as an argument to a higher-order function.当我们将其用作高阶函数的参数时,这很有帮助。 Eg: A function that takes in other functions as arguments.例如:一个接受其他函数作为参数的函数。

Example of Function definition:函数定义示例:

>>> def func(a, b):
    return a * b

>>> func(2,3)
6
>>> type(func)
<class 'function'>
>>> func
<function func at 0x034B6E88>

Example of Lambda expression: Lambda 表达式示例:

>>> multiply = lambda a, b: a * b
>>> multiply(2, 3)
6
>>> type(multiply)
<class 'function'>
>>> multiply
<function <lambda> at 0x034B6ED0>

Both returns same output value.两者都返回相同的输出值。 Only object returned are different.只有返回的对象不同。 "func" name for Function and for Lambda.函数和 Lambda 的“func”名称。

First consider the diff b/w the two.首先考虑两者的差异黑白。

Lambda functions: are operator can have any number of arguments, but it can have only one expression. Lambda 函数: are 运算符可以有任意数量的参数,但只能有一个表达式。 It cannot contain any statements and it returns a function object which can be assigned to any variable.它不能包含任何语句,它返回一个可以分配给任何变量的函数对象。 They can be used in the block they were created.它们可以在它们创建的块中使用。

def functions: Functions help break our program into smaller and modular chunks. def 函数:函数有助于将我们的程序分解成更小的模块化块。 As our program grows larger and larger, functions make it more organised and manageable.随着我们的程序变得越来越大,函数使它更有条理和易于管理。 They can be called and used anywhere we want.它们可以在我们想要的任何地方调用和使用。

Here you can get more clear difference by following example.在这里,您可以通过以下示例获得更明显的区别。

Defining a function定义函数

    def add(a,b):
      return a+b
    print(add(4,5))

Defining a lambda定义一个 lambda

    add = lambda x, y : x + y 
    print(add(4,5))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 python lambda和常规函数之间一定有区别吗? - there must be some difference between python lambda and regular function? Python中这两个lambda函数有什么区别? - What is the difference between these two lambda functions in Python? Swift 闭包、Java 闭包和 ZA7F5F35426B927411FC9231B56BB382173Z Z04A7DA3C5B04CAD8BZDAEE 表达式有什么区别? - What is the difference between Swift Closures, Java Closures, and Python Lambda expressions? 这两个解决方案有什么区别 - lambda或loop - Python - What is the difference between these two solutions - lambda or loop - Python .* 和.* 有什么区别? 在正则表达式中? - What is the difference between .* and .*? in a regular expression? 在 python ZE5BA8B4C39C29BF13426EF5E0287AAA55 按钮命令中使用与不使用 lambda function 的区别 - Difference between using or not lambda function in python tkinter button command Python:将 lambda 函数和类名作为参数传递之间的区别 - Python: Difference between passing lambda function and class name as arguments Python 中的语句和函数有什么区别? - What is the difference between a statement and a function in Python? python 中 // 和 //= 有什么区别? - What is the difference between // and //= in python? Python 中的:= 和::= 有什么区别? - What is the difference between := and ::= in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM