Python函数句柄ala Matlab [英] Python function handle ala Matlab

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

问题描述

在MATLAB中,可以创建 function handles

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

myfun=@(arglist)body

通过这种方式,您可以随时随地创建函数,而无需创建M文件.

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

Python中是否有等效的方法可以在一行中声明函数和变量并在以后调用它们?

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

推荐答案

Python的lambda函数有些相似:

Python's lambda functions are somewhat similar:

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

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

但是,您可以通过简单地将fn()定义为函数来实现类似的效果:

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

普通"(与lambda相对)功能更灵活,因为它们允许条件语句,循环等.

"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.

最后,Python中的函数是一流的对象.这意味着,除其他外,您可以将它们作为参数传递给其他函数.这适用于上面显示的两种功能.

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.

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

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