Python相当于JavaScript函数对象。 [英] Python equivalent to JavaScript function object.

查看:84
本文介绍了Python相当于JavaScript函数对象。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaEE过去两年一直在开发fullstack。我想清除我的Python知识
所以我想知道是否有一个Python等效于这个JavaScript构造,我希望将涉及使用Python字典:

I have been developing fullstack for the last two years in JavaEE. I would like to dust off my Python knowledge so I would like to know if there is a Python equivalent to this JavaScript construct, that I supponse will involve using Python dictionaries:

var myFunctions = {
    'greet': function(name){
        return "Hello, " + name;
    },

    'farewell': function(time){
        return "See you " + time;
    }
}

所以我可以这样调用函数:

So I can call the functions this way:

let greetMarta = myFunctions['greet']("Marta");


推荐答案

您可以使用 lambda 定义非常简单的函数,如这些内联;但是它们只能由一个表达式组成:

You can use lambda to define very simple functions like these inline; however they can only consist of one expression:

my_functions = {
    'greet': lambda name: "Hello {}".format(name),
    'farewell': lambda time: "See you {}".format(time)
}

对于任何更复杂的东西,你需要定义一个独立的函数,然后在dict中引用它:

For anything more complicated you need to define a standalone function and then reference it in the dict:

def my_complex_function(param):
    ... logic ...
    return whatever

my_functions = {
    'complex_func': my_complex_function,
    ...
}

这篇关于Python相当于JavaScript函数对象。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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