Reputation: 352
In JS I can define an Object like this:
foo = {"foo": 42, "bar": function(){/* do something */}}
Is there a way to do the same thing in Python ?
Upvotes: 4
Views: 298
Reputation: 8541
Python has lambda
function. A lambda
function is a small anonymous function. A lambda
function can take any number of arguments, but can only have one expression.
Syntax:
lambda arguments : expression
Can you try the following:
foo = {"foo": 42, "bar": lambda a : a + 10}
And you can use it in the following way:
foo['bar'](5)
You will get the following output:
15
Entire example:
>>> foo = {"foo": 42, "bar": lambda a : a + 10}
>>> foo['bar'](5)
15
You can also call a standard function the same way refer the other solution by Loss of human identity.
Example
def my_func(a):
return a + 10
foo = {"foo": 42, "bar": my_func}
foo['bar'](5)
# output
# 15
Upvotes: 5
Reputation: 3233
The following might work:
# Define a function
def foo():
print("foo")
# Define a dictionary
d = {"a":1, "b":foo}
d["b"]()
Output: foo
Upvotes: 6