问题描述
我在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 knowledgeso 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函数对象。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!