简体   繁体   English

根据lambda表达式定义命名函数和使用`def`之间是否存在差异?

[英]Are there difference between defining a named function in terms of lambda expressions and using `def`?

Are there difference between defining a named function in terms of lambda expressions and using def ? 根据lambda表达式定义命名函数和使用def有区别吗?

For example, are the following two ways defining two equivalent functions? 例如,以下两种方式定义两个等效函数?

adder = lambda x, y: x+y

and

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

Thanks. 谢谢。

Structurally they are equivalent. 在结构上它们是等价的。 BUT, from PEP 8 : 但是,从PEP 8

Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier. 始终使用def语句而不是将lambda表达式直接绑定到标识符的赋值语句。

Yes: def f(x): return 2*x 是: def f(x): return 2*x

No: f = lambda x: 2*x 否: f = lambda x: 2*x

The first form means that the name of the resulting function object is specifically 'f' instead of the generic 'lambda'. 第一种形式意味着生成的函数对象的名称特别是'f'而不是通用的'lambda'。 This is more useful for tracebacks and string representations in general. 这对于一般的回溯和字符串表示更有用。 The use of the assignment statement eliminates the sole benefit a lambda expression can offer over an explicit def statement (ie that it can be embedded inside a larger expression 赋值语句的使用消除了lambda表达式在显式def语句上提供的唯一好处(即它可以嵌入到更大的表达式中

So, this implies you should only use lambdas embedded in larger expressions, for the sake of terser code, rather than assigning an object to them, where the benefit of aesthetic neatness is overwhelmed by the disadvantages named above. 因此,这意味着你应该只使用嵌入在较大表达式中的lambdas,为了更简洁的代码,而不是为它们分配一个对象,其中美学整洁的好处被上面提到的缺点所淹没。

Outside of having a name that is convenient for printing, in that example no. 除了具有便于打印的名称之外,在该示例中没有。 A big difference in general though, is you cannot have statements inside a lambda (doesn't apply to your example, but worth knowing). 一般来说,一个很大的区别是,你不能在lambda中包含语句(不适用于你的例子,但值得了解)。

For example: 例如:

def foo():
    x = 2 #can't do in lambda
    return x

Long story short, there is no difference. 长话短说,没有区别。 The only minor difference is the absence of a specific name embedded into the function object. 唯一的细微差别是缺少嵌入到函数对象中的特定名称。 This makes some tools, such as Python's built-in multiprocessing incompatible with lambda-functions, (in case of multiprocessing it is due to pickle 's inability to serialise lambdas), though a similar package multiprocess does support them. 这使得一些工具,例如Python的内置multiprocessing与lambda函数不兼容(在multiprocessing情况下,它是由于pickle无法序列化lambda),尽管类似的包multiprocess确实支持它们。

There is a difference. 它们是有区别的。 Lambdas make it much easier to produce closures which may behave in an unexpected way. Lambdas可以更容易地生成可能以意想不到的方式运行的闭包。

Here's an example: 这是一个例子:

def create_multipliers_fun():
    def multiplier_factory(i):
        def multiplier(x):
            return i * x
        return multiplier
    # here, an array of functions is returned
    # each multiplies the input value by the value `i` received in the loop
    return [multiplier_factory(i) for i in range(5)]

# prints 0 2 4 6 8
for multiplier in create_multipliers_fun():
    print multiplier(2)

def create_multipliers_lambda():
    # here, all returned functions use the latest available version
    # of the variable `i` (closure with late binding) 
    return [lambda x : i * x for i in range(5)]

# prints 8 8 8 8 8
for multiplier in create_multipliers_lambda():
    print multiplier(2)

Using lambdas it's much less obvious that you're dealing with a late binding closure. 使用lambdas,你处理一个后期绑定闭包更不明显。

For comparison: 为了比较:

def create_multipliers_closure():
    def multiplier(x):
        return i * x
    return [multiplier for i in range(5)]

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

相关问题 使用lambda作为函数与将lambda与map一起使用有什么区别吗? - Is there any difference between using lambda as a function and using lambda with map? 类和def中的python lambda函数之间的区别 - Difference between python lambda functions inside class and def 使用lambda表达式查找列表中每两个相邻元素之间的区别? - Find difference between every two adjacent elements in a list using lambda expressions? 将 lambda 与命名 function 应用到 pandas ZBA834BA059A97EB88 之间的性能差异 - Performance difference between applying lambda vs. named function to a pandas DataFrame 在 python ZE5BA8B4C39C29BF13426EF5E0287AAA55 按钮命令中使用与不使用 lambda function 的区别 - Difference between using or not lambda function in python tkinter button command Swift 闭包、Java 闭包和 ZA7F5F35426B927411FC9231B56BB382173Z Z04A7DA3C5B04CAD8BZDAEE 表达式有什么区别? - What is the difference between Swift Closures, Java Closures, and Python Lambda expressions? 将 lambda function 写为 def:-function - Write lambda function as def:-function 有没有办法通过使用 apply 和 lambda 来编写 function “def” - Is there any way to write function “def” by using apply and lambda 如何使用Lambda表达式实现递归函数 - How to implement a recursive function using lambda expressions 使用 Lambda 表达式折叠高阶 Function - Fold Higher Order Function Using Lambda Expressions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM