类似于Matlab的Python函数处理
在MATLAB中,你可以用一些简单的代码来创建函数句柄
,像这样:
myfun=@(arglist)body
这样你就可以随时创建函数,而不需要事先写好M文件。
那么在Python中,有没有类似的方法可以在一行中声明函数和变量,然后再调用它们呢?
3 个回答
0
原来有一个东西可以追溯到2.5版本,叫做函数偏应用,它和函数句柄的概念非常相似。
from functools import partial
def myfun(*args, first="first default", second="second default", third="third default"):
for arg in args:
print(arg)
print("first: " + str(first))
print("second: " + str(second))
print("third: " + str(third))
mypart = partial(myfun, 1, 2, 3, first="partial first")
mypart(4, 5, second="new second")
1
2
3
4
5
first: partial first
second: new second
third: third default
15
这不是完整的答案。在matlab中,可以创建一个名为funct.m的文件:
function funct(a,b)
disp(a*b)
end
在命令行中:
>> funct(2,3)
6
然后,可以创建一个函数句柄,比如:
>> myfunct = @(b)funct(10,b))
接着可以这样做:
>> myfunct(3)
30
一个完整的答案会告诉你如何在python中做到这一点。
下面是具体的做法:
def funct(a,b):
print(a*b)
然后:
myfunct = lambda b: funct(10,b)
最后:
>>> myfunct(3)
30
17
Python中的lambda函数有点像:
In [1]: fn = lambda x: x**2 + 3*x - 4
In [2]: fn(3)
Out[2]: 14
不过,你也可以通过简单地把fn()
定义为一个普通函数来达到类似的效果:
In [1]: def fn(x):
...: return x**2 + 3*x - 4
...:
In [2]: fn(4)
Out[2]: 24
所谓“普通”函数(和lambda函数相对)更灵活,因为它们可以使用条件语句、循环等。
没有必要把函数放在专门的文件里或者其他类似的地方。
最后,Python中的函数是第一类对象。这意味着,除了其他特性外,你可以把它们作为参数传递给其他函数。这两种类型的函数都适用这个规则。