与Ruby相比,Python的局限性:lambda的 [英] Restrictons of Python compared to Ruby: lambda's

查看:117
本文介绍了与Ruby相比,Python的局限性:lambda的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在浏览WikiVS的某些页面,引自以下内容:

I was going over some pages from WikiVS, that I quote from:

因为Python中的lambda仅限于表达式且不能 包含语句

because lambdas in Python are restricted to expressions and cannot contain statements

我想知道这个限制(最好是与Ruby语言相比)的一个好例子(或更多例子).

I would like to know what would be a good example (or more) where this restriction would be, preferably compared to the Ruby language.

感谢您的回答,评论和反馈!

Thank you for your answers, comments and feedback!

推荐答案

我认为您并不是真正在问lambda,而是内联函数.

I don't think you're really asking about lambdas, but inline functions.

这确实是Python严重令人讨厌的限制之一:您不能内联定义一个函数(一个真正的函数,而不仅仅是一个表达式);您必须给它起个名字.这非常令人沮丧,因为其他所有现代脚本语言都可以做到这一点,而不得不离线移动函数通常会非常痛苦.这也令人沮丧,因为我感到Python字节码可以轻松地表示这一点-只是语言语法不能做到这一点.

This is genuinely one of Python's seriously annoying limitations: you can't define a function (a real function, not just an expression) inline; you have to give it a name. This is very frustrating, since every other modern scripting language does this and it's often very painful to have to move functions out-of-line. It's also frustrating because I have a feeling Python bytecode can represent this trivially--it's just the language syntax that can't.

JavaScript:

Javascript:

responses = {
        "resp1": {
                "start": function() { ...  },
                "stop": function() { ... },
        },
        "resp2": {
                "start": function() { ...  },
                "stop": function() { ... },
        },
        ...
}
responses["resp1"]["start"]();

卢阿:

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:它们没有理由存在,因为内联函数以更加自然和通用的方式覆盖了它们.

Note that JavaScript and Lua don't have lambdas: they have no reason to exist, since inline functions cover them in a much more natural and general way.

我可能会将此视为每天最烦人的Python限制.

I'd probably rate this as the single most annoying day-to-day Python limitation.

这篇关于与Ruby相比,Python的局限性:lambda的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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