我在试着找出Python的lambda。lambda是那些在现实生活中应该被遗忘的“有趣”语言项之一吗?
我确信有一些边缘情况可能需要它,但是考虑到它的模糊性,它在未来版本中被重新定义的可能性(我基于它的各种定义的假设)以及降低的编码清晰度——应该避免它吗?
这让我想起了C类型的溢出(缓冲区溢出)——指向顶部变量并重载以设置其他字段值。这感觉有点像技术人员的表演,但维护程序员的噩梦。
我在试着找出Python的lambda。lambda是那些在现实生活中应该被遗忘的“有趣”语言项之一吗?
我确信有一些边缘情况可能需要它,但是考虑到它的模糊性,它在未来版本中被重新定义的可能性(我基于它的各种定义的假设)以及降低的编码清晰度——应该避免它吗?
这让我想起了C类型的溢出(缓冲区溢出)——指向顶部变量并重载以设置其他字段值。这感觉有点像技术人员的表演,但维护程序员的噩梦。
当前回答
lambdas在GUI编程中非常有用。例如,假设您正在创建一组按钮,并且希望使用单个参数化回调,而不是每个按钮使用唯一的回调。Lambda让你轻松完成:
for value in ["one","two","three"]:
b = tk.Button(label=value, command=lambda arg=value: my_callback(arg))
b.pack()
(注意:虽然这个问题是专门问lambda的,但你也可以使用functools。以获得相同类型的结果)
另一种方法是为每个按钮创建单独的回调,这可能导致重复的代码。
其他回答
首先恭喜你算出了。在我看来,这是一个非常强大的构念。如今函数式编程语言的发展趋势无疑表明,在不久的将来,它既不应该被避免,也不会被重新定义。
你只需要换个角度思考。我相信你很快就会爱上它的。但是如果你只和python打交道要小心。因为lambda不是一个真正的闭包,它以某种方式“坏了”:python的lambda坏了
两行总结:
闭包:非常有用。学习它们,利用它们,热爱它们。 Python的lambda关键字:不必要,偶尔有用。如果你发现自己在用它做任何复杂的事情,把它放在一边,定义一个真正的函数。
lambdas在GUI编程中非常有用。例如,假设您正在创建一组按钮,并且希望使用单个参数化回调,而不是每个按钮使用唯一的回调。Lambda让你轻松完成:
for value in ["one","two","three"]:
b = tk.Button(label=value, command=lambda arg=value: my_callback(arg))
b.pack()
(注意:虽然这个问题是专门问lambda的,但你也可以使用functools。以获得相同类型的结果)
另一种方法是为每个按钮创建单独的回调,这可能导致重复的代码。
我刚开始学习Python,然后一头栽进Lambda——这花了我一段时间才弄明白。
请注意,这不是对任何事情的谴责。每个人都有不容易得到的东西。
lambda是那些在现实生活中应该被遗忘的“有趣”语言项目之一吗?
No.
我相信有一些边缘情况可能需要它,但考虑到它的模糊性,
它并不晦涩。在我过去工作过的两个团队中,每个人都一直在使用这个功能。
它在未来版本中被重新定义的可能性(我基于它的各种定义的假设)
除了几年前修复闭包语义之外,我还没有看到在Python中重新定义它的严肃建议。
编码清晰度的降低——应该避免吗?
如果你用对了,也不会不太清楚。相反,拥有更多可用的语言结构可以增加清晰度。
这让我想起了C类型的溢出(缓冲区溢出)——指向顶部变量并重载以设置其他字段值……有点像技术人员的表演技巧,但维护程序员的噩梦。
就像缓冲区溢出?哇。如果您认为lambda是一个“维护噩梦”,我无法想象您将如何使用它。
I started reading David Mertz's book today 'Text Processing in Python.' While he has a fairly terse description of Lambda's the examples in the first chapter combined with the explanation in Appendix A made them jump off the page for me (finally) and all of a sudden I understood their value. That is not to say his explanation will work for you and I am still at the discovery stage so I will not attempt to add to these responses other than the following: I am new to Python I am new to OOP Lambdas were a struggle for me Now that I read Mertz, I think I get them and I see them as very useful as I think they allow a cleaner approach to programming.
He reproduces the Zen of Python, one line of which is Simple is better than complex. As a non-OOP programmer reading code with lambdas (and until last week list comprehensions) I have thought-This is simple?. I finally realized today that actually these features make the code much more readable, and understandable than the alternative-which is invariably a loop of some sort. I also realized that like financial statements-Python was not designed for the novice user, rather it is designed for the user that wants to get educated. I can't believe how powerful this language is. When it dawned on me (finally) the purpose and value of lambdas I wanted to rip up about 30 programs and start over putting in lambdas where appropriate.