Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python function handle ala Matlab

Tags:

python

matlab

In MATLAB it is possible to create function handles with something like

myfun=@(arglist)body

This way you can create functions on the go without having to create M-files.

Is there an equivalent way in Python to declare functions and variables in one line and to call them later?

like image 202
Leon palafox Avatar asked Apr 21 '11 11:04

Leon palafox


People also ask

Does Python have function handles?

Function handles can also be passed as arguments in Matlab. @MatlabSorter: In python a function (or a lambda) can be passed as an argument to another function. You don't need a "handle", you just pass the function itself.

Is function handle MATLAB?

A function handle is a MATLAB® data type that represents a function. A typical use of function handles is to pass a function to another function. For example, you can use function handles as input arguments to functions that evaluate mathematical expressions over a range of values.

How do you handle a function in Python?

The four steps to defining a function in Python are the following: Use the keyword def to declare the function and follow this up with the function name. Add parameters to the function: they should be within the parentheses of the function. End your line with a colon.


2 Answers

Python's lambda functions are somewhat similar:

In [1]: fn = lambda x: x**2 + 3*x - 4

In [2]: fn(3)
Out[2]: 14

However, you can achieve similar effects by simply defining fn() as a function:

In [1]: def fn(x):
   ...:   return x**2 + 3*x - 4
   ...: 

In [2]: fn(4)
Out[2]: 24

"Normal" (as opposed to lambda) functions are more flexible in that they allow conditional statements, loops etc.

There's no requirement to place functions inside dedicated files or anything else of that nature.

Lastly, functions in Python are first-class objects. This means, among other things, that you can pass them as arguments into other functions. This applies to both types of functions shown above.

like image 112
NPE Avatar answered Sep 30 '22 05:09

NPE


This is not quite the full answer. In matlab, one can make a file called funct.m:

function funct(a,b)
   disp(a*b)
end

At the command line:

>> funct(2,3)
     6

Then, one can create a function handle such as:

>> myfunct = @(b)funct(10,b))

Then one can do:

   >> myfunct(3)
       30

A full answer would tell how to do this in python.

Here is how to do it:

def funct(a,b):
    print(a*b)

Then:

myfunct = lambda b: funct(10,b)

Finally:

>>> myfunct(3)
30
like image 34
abalter Avatar answered Sep 30 '22 05:09

abalter