Python函数作为函数参数?

a76*_*664 103 python arguments function

Python函数可以作为另一个函数的参数吗?

说:

def myfunc(anotherfunc, extraArgs):
    # run anotherfunc and also pass the values from extraArgs to it
    pass
Run Code Online (Sandbox Code Playgroud)

所以这基本上是两个问题:

  1. 它是否允许?
  2. 如果是,如何在其他功能中使用该功能?我需要使用exec(),eval()或类似的东西吗?永远不需要弄乱它们.

BTW,extraArgs是anotherfunc参数的列表/元组.

Man*_*res 122

Python函数可以作为另一个函数的参数吗?

是.

def myfunc(anotherfunc, extraArgs):
    anotherfunc(*extraArgs)
Run Code Online (Sandbox Code Playgroud)

更具体......各种论点......

>>> def x(a,b):
...     print "param 1 %s param 2 %s"%(a,b)
...
>>> def y(z,t):
...     z(*t)
...
>>> y(x,("hello","manuel"))
param 1 hello param 2 manuel
>>>
Run Code Online (Sandbox Code Playgroud)

  • 这是在哪里记录的? (4认同)
  • @4dc0我不认为它是*直接*记录的;这只是 Python 数据模型工作方式的自然结果。一切可以与名称绑定的东西都是对象;对象可以传递给函数;函数可以绑定到一个名称(这就是使用“def”时发生的情况);因此,函数可以传递给函数。也就是说,您可能对 https://docs.python.org/3.11/howto/featured.html 感兴趣,它展示了“利用”这一现实的基本技术,并展示了一些*设计的标准库好东西利用*它。 (2认同)

sab*_*ujp 32

这是使用*args(以及可选)的另一种方式**kwargs:

def a(x, y):
  print x, y

def b(other, function, *args, **kwargs):
  function(*args, **kwargs)
  print other

b('world', a, 'hello', 'dude')
Run Code Online (Sandbox Code Playgroud)

产量

hello dude
world
Run Code Online (Sandbox Code Playgroud)

需要注意的是function,*args,**kwargs必须按照这个顺序和必须的函数调用该函数的最后的参数.

  • 关于*args&**kwargs的更多信息可以在这里找到https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/ (2认同)

Ign*_*ams 16

Python中的函数是一流的对象.但是你的功能定义有点偏.

def myfunc(anotherfunc, extraArgs, extraKwArgs):
  return anotherfunc(*extraArgs, **extraKwArgs)
Run Code Online (Sandbox Code Playgroud)


Art*_*nka 5

当然,这就是为什么 python 实现以下第一个参数是函数的方法:

  • map(function, iterable, ...)- 将函数应用于可迭代的每个项目并返回结果列表。
  • filter(function, iterable)- 从函数返回 true 的 iterable 元素构造一个列表。
  • reduce(function, iterable [,initializer])iterable-从左到右将两个参数的函数累加到 的项上,从而将可迭代减少为单个值。
  • 拉姆达


归档时间:

查看次数:

176975 次

最近记录:

6 年,7 月 前