Python function handle ala Matlab

前端 未结 3 897
面向向阳花
面向向阳花 2021-02-13 19:19

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

myfun=@(arglist)body

This way you can create functions on the go withou

3条回答
  •  孤城傲影
    2021-02-13 20:07

    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.

提交回复
热议问题