Python函数作为函数参数? [英] Python function as a function argument?

查看:31
本文介绍了Python函数作为函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

说:

def myfunc(anotherfunc, extraArgs):# 运行 anotherfunc 并将值从 extraArgs 传递给它经过

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

  1. 完全允许吗?
  2. 如果是,我如何在另一个函数中使用该函数?我需要使用 exec()、eval() 或类似的东西吗?从来不需要惹他们.

顺便说一句,extraArgs 是 anotherfunc 参数的列表/元组.

解决方案

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

是的.

def myfunc(anotherfunc, extraArgs):anotherfunc(*extraArgs)

更具体地说......有各种参数......

<预><代码>>>>定义 x(a,b):...打印参数 1 %s 参数 2 %s"%(a,b)...>>>定义 y(z,t):... z(*t)...>>>y(x,("你好","曼努埃尔"))参数 1 你好参数 2 曼努埃尔>>>

Can a Python function be an argument of another function?

Say:

def myfunc(anotherfunc, extraArgs):
    # run anotherfunc and also pass the values from extraArgs to it
    pass

So this is basically two questions:

  1. Is it allowed at all?
  2. And if it is, how do I use the function inside the other function? Would I need to use exec(), eval() or something like that? Never needed to mess with them.

BTW, extraArgs is a list/tuple of anotherfunc's arguments.

解决方案

Can a Python function be an argument of another function?

Yes.

def myfunc(anotherfunc, extraArgs):
    anotherfunc(*extraArgs)

To be more specific ... with various arguments ...

>>> 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
>>>

这篇关于Python函数作为函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆