matlab函数'handle'和python函数'object'的区别

Difference between matlab function 'handle' and python function 'object'

有人在 this comment 中提出,Matlab 和 Python 传递函数的方式不同。从我通过查看和使用两者可以看出,两者之间没有区别,但也许我遗漏了什么?

在 Matlab 中,您可以像这样创建一个快速函数句柄:

fun = @(x) x.^2 + 1;

在 Python 中,使用 lambda 函数,您可以创建类似这样的函数:

def fun(x):
    return x^2

在这两种语言中,可以将术语 'fun' 作为参数发送到另一个函数 - 但我链接到的评论者暗示它们不一样 and/or 需要以不同的方式使用.

我错过了什么?

第一条评论似乎只是重申了您可以将 MATLAB 函数句柄作为参数传递的想法(尽管答案没有说明任何让我不这么认为的内容)。第二条评论似乎将此解释为第一条评论者认为您 无法 在 Python 中执行此操作并回复说您可以使用 lambda 或 直接传递函数

无论如何,假设您正确使用它们,MATLAB 中的函数句柄在功能上等同于使用 lambda 或函数对象作为 Python 中的输入参数.

在 python 中,如果您不将 () 附加到函数的末尾,它不会执行该函数,而是生成函数对象,然后可以将其传递给另一个功能。

# Function which accepts a function as an input
def evalute(func, val)
    # Execute the function that's passed in
    return func(val)

# Standard function definition
def square_and_add(x):
    return x**2 + 1

# Create a lambda function which does the same thing. 
lambda_square_and_add = lambda x: x**2 + 1

# Now pass the function to another function directly
evaluate(square_and_add, 2)

# Or pass a lambda function to the other function
evaluate(lambda_square_and_add, 2)

在 MATLAB 中,您必须使用函数句柄,因为即使您省略 ().

,MATLAB 也会尝试执行函数
function res = evaluate(func, val)
    res = func(val)
end

function y = square_and_add(x)
    y = x^2 + 1;
end

%// Will try to execute square_and_add with no inputs resulting in an error
evaluate(square_and_add)

%// Must use a function handle
evaluate(@square_and_add, 2)