在MATLAB中,可以通过类似以下方式创建函数句柄
:
myfun=@(arglist)body
通过这种方式,您可以在不必创建M文件的情况下即可创建函数。
在Python中是否有一种等效的方法可以在一行中声明函数和变量,并稍后调用它们?
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中,函数是一级对象。这意味着,您可以将它们作为参数传递给其他函数。这适用于上述两种类型的函数。
这不是完整的答案。在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
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
lambda
吗?def
有什么问题吗? - S.Lott