【问题标题】:Python function handle ala MatlabPython 函数句柄 ala Matlab
【发布时间】:2011-04-21 11:12:39
【问题描述】:

在 MATLAB 中,可以使用类似的东西创建 function handles

myfun=@(arglist)body

这样您就可以随时随地创建函数,而无需创建 M 文件。

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

【问题讨论】:

  • 您在寻找lambda吗? def 怎么了?

标签: python matlab


【解决方案1】:

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 中作为参数传递。
  • @MatlabSorter:在 python 中,函数(或 lambda)可以作为参数传递给另一个函数。您不需要“句柄”,只需传递函数本身即可。
【解决方案2】:

这不是完整的答案。在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

【讨论】:

    【解决方案3】:

    原来有一个东西可以追溯到 2.5,称为function partials,它几乎完全类似于函数句柄。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-30
      • 2019-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多