简体   繁体   English

在python中将函数作为参数传递

[英]passing function as arguments in python

I am trying to get my head around this one. 我想试试这个问题。

So here is what I want to do: I have three functions. 所以这就是我想要做的:我有三个功能。 say, foo,bar and foo_bar 比如说,foo,bar和foo_bar

def foo_bar(function):
   for i in range(20):
      function # execute function
def foo(someargs):
   print "hello from foo"

def bar(someargs):
   print " hello from bar"

and when i do foo_bar(foo) # how to specify arguments to foo?? 当我做foo_bar(foo) # how to specify arguments to foo??

I am expecting that I see "hello from foo" 20 times ? 我期待我看到"hello from foo" 20 times

But since I am not seeing that.. I clearly dont understand this well enough? 但是因为我没有看到这一点......我显然不太清楚这一点吗?

You're not calling the function. 你没有调用这个函数。 You call a function called function by following the name function with brackets () , and inside those brackets you put any arguments you need: function通过使用括号()跟随名称function调用一个名为functionfunction ,并在这些括号中放置您需要的任何参数:

function(function)

I've passed function as a parameter to itself because your foo and bar take arguments, but do nothing with them. 我已经将函数作为参数传递给了它自己,因为你的foobar接受了参数,但对它们没有任何作用。

This should do basically what you want: 这基本上应该做你想要的:

def foo_bar(function):
   for i in range(20):
      function(i) # execute function
def foo(someargs):
   print "hello from foo"

def bar(someargs):
   print " hello from bar"

foo_bar(foo)
foo_bar(bar)

The docs have a section on this here . 文档在这里有一节。 You most likely want to construct foo_bar as 你很可能想把foo_bar构造成

def foo_bar(function, *func_args):
    for i in range(20):
        function(func_args)

def foo(a):
    print "hello %s"%a

You can then call it as 然后你可以把它称为

foo_bar(foo, 'from foo!')

I would make foo_bar return a function that accept the parameters to pass to the internal function: 我会让foo_bar返回一个接受传递给内部函数的参数的函数:

def foo_bar(fn, n=20):
    def _inner(*args, **kwargs):
        for i in range(n):
            fn(*args, **kwargs)
    return _inner

and call it like: 并称之为:

foo_bar(foo)('some_param')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM