我不认为你真的在问 lambda,但是内联函数.
这确实是 Python 非常恼人的限制之一:你不能内联定义一个函数(一个真正的函数,而不仅仅是一个表达式);你必须给它一个名字。这是非常令人沮丧的,因为所有其他现代脚本语言都这样做,并且必须将函数移出线外通常是非常痛苦的。这也令人沮丧,因为我有一种感觉 Python 字节码可以简单地表示这一点——只是语言语法不能。
JavaScript:
responses = {
"resp1": {
"start": function() { ... },
"stop": function() { ... },
},
"resp2": {
"start": function() { ... },
"stop": function() { ... },
},
...
}
responses["resp1"]["start"]();
Lua:
responses = {
resp1 = {
start = function() ... end;
end = function() ... end;
};
...
}
responses.resp1.start();
Ruby:
responses = {
"resp1" => {
"start" => lambda { },
"stop" => lambda { },
},
}
responses["resp1"]["start"].call
Python:
def resp1_start():
pass
def resp1_stop():
pass
responses = {
"resp1": {
"start": resp1_start,
"stop": resp1_stop,
},
}
responses["resp1"]["start"]()
请注意,JavaScript 和 Lua 没有 lambda:它们没有存在的理由,因为内联函数以更自然和通用的方式覆盖它们。
我可能会将其视为日常 Python 中最烦人的限制。