lambda 和常规函数之间的 python 有什么区别? [英] what is the difference for python between lambda and regular function?

查看:33
本文介绍了lambda 和常规函数之间的 python 有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇 lambda 函数和常规函数(用 def 定义)之间的区别 - 在 python 级别.(我知道程序员有什么区别以及何时使用它们.)

<预><代码>>>>定义一个():返回 1>>>b = 拉姆达:1>>>一个<函数 a 在 0x0000000004036F98>>>>乙<函数<lambda>在 0x0000000004031588>

正如我们所见 - python 知道 b 是一个 lambda 函数,而 a 是一个常规函数.这是为什么?它们到python有什么区别?

解决方案

它们的类型相同,所以处理方式相同:

<预><代码>>>>类型(一)<输入'函数'>>>>类型(b)<输入'函数'>

Python 也知道 b 被定义为一个 lambda 函数并将其设置为函数名:

<预><代码>>>>a.func_name'一个'>>>b.func_name'<拉姆达>'

换句话说,它会影响函数将获得的名称,但就 Python 而言,两者都是函数,这意味着它们主要可以以相同的方式使用.有关酸洗的函数和 lambda 函数之间的重要区别,请参阅下面的 mgilson 评论.

I'm curious about the difference between lambda function and a regular function (defined with def) - in the python level. (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? what is the difference between them to 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:

>>> 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. See mgilson's comment below for an important difference between functions and lambda functions regarding pickling.

这篇关于lambda 和常规函数之间的 python 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆