Python—将函数传递给另一个函数

时间:2022-12-05 19:12:32

I am solving a puzzle using python and depending on which puzzle I am solving I will have to use a special set of rules. How can I pass a function into another function in Python?

我正在使用python解决一个难题,根据我正在解决的难题,我必须使用一组特殊的规则。如何在Python中将函数传递给另一个函数?

Example

例子

def Game(listA, listB, rules):
   if rules == True:
      do...
   else:
      do...

def Rule1(v):
  if "variable_name1" in v:
      return False
  elif "variable_name2" in v:
      return False
  else:
      return True

def Rule2(v):
  if "variable_name3" and "variable_name4" in v:
      return False
  elif "variable_name4" and variable_name1 in v:
      return False
  else:
      return True

This is just a pseudo code and therefore not specific but I get the code to compile but I need to know how to call the function Game and whether it's correctly defined since rules will be switched for either Rule1(v) or Rule2(v).

这只是一个伪代码,因此并不特定,但是我需要编译代码,但是我需要知道如何调用函数博弈,以及它是否被正确定义,因为规则将被转换为Rule1(v)或Rule2(v)。

5 个解决方案

#1


102  

Just pass it in like any other parameter:

就像其他参数一样传入它:

def a(x):
    return "a(%s)" % (x,)

def b(f,x):
    return f(x)

print b(a,10)

#2


16  

Treat function as variable in your program so you can just pass them to other functions easily:

把函数当作程序中的变量,这样你就可以很容易地将它们传递给其他函数:

def test ():
   print "test was invoked"

def invoker(func):
   func()

invoker(test)  # prints test was invoked

#3


8  

A function name can become a variable name (and thus be passed as an argument) by dropping the parentheses. A variable name can become a function name by adding the parentheses.

通过删除括号,函数名可以成为变量名(因此作为参数传递)。通过添加括号,变量名可以成为函数名。

In your example, equate the variable rules to one of your functions, leaving off the parentheses and the mention of the argument. Then in your game() function, invoke rules( v ) with the parentheses and the v parameter.

在您的示例中,将变量规则与您的函数之一等同起来,去掉括号和参数的说明。然后在game()函数中,使用括号和v参数调用规则(v)。

if puzzle == type1:
    rules = Rule1
else:
    rules = Rule2

def Game(listA, listB, rules):
    if rules( v ) == True:
        do...
    else:
        do...

#4


7  

Just pass it in, like this:

把它传递进去,就像这样:

Game(list_a, list_b, Rule1)

and then your Game function could look something like this (still pseudocode):

然后你的游戏函数可以是这样的(仍然是伪代码)

def Game(listA, listB, rules=None):
    if rules:
        # do something useful
        # ...
        result = rules(variable) # this is how you can call your rule
    else:
        # do something useful without rules

#5


6  

A generalized approach

一个通用的方法

For passing both a function, and the parameters to the function (e.g. using the same iteration routine for different functions) consider the following (python2.x) example:

要将函数和参数传递给函数(例如,对不同的函数使用相同的迭代例程),请考虑以下示例(python2.x):

def test(a, b):
    '''The function to pass'''
    print a+b

def looper(func, **kwargs):
    '''A basic iteration function'''
    for i in range(5):
        # Our passed function with passed parameters
        func(*tuple(value for _, value in kwargs.iteritems()))

if __name__ == '__main__':
    # This will print `3` five times
    looper(test, a=1, b=2)

Some explanation

一些解释

  • tuple( i for i in (1, 2, 3)) is a tuple generator, creating a tuple from the items in a list, set, tuple... in our case, the values from **kwargs
  • tuple(我在(1、2、3)中)是一个tuple生成器,从列表中的项创建一个tuple, set、tuple…在我们的例子中,来自**kwargs的值
  • the * in front of the tuple() will unpack its contents, effectively passing them as parameters to the passed function
  • tuple()前面的*将解压它的内容,有效地将它们作为参数传递给传递的函数
  • _ in the generator is just a place holder for the key, since we aren't using that
  • 发电机里的_只是钥匙的存放位置,因为我们不用它

For python3.x:

python3.x:

  • print(a+b) instead of print a+b
  • 打印(a+b)而不是打印a+b
  • kwargs.items() instead of kwargs.iteritems()
  • kwargs.items代替kwargs.iteritems()()

#1


102  

Just pass it in like any other parameter:

就像其他参数一样传入它:

def a(x):
    return "a(%s)" % (x,)

def b(f,x):
    return f(x)

print b(a,10)

#2


16  

Treat function as variable in your program so you can just pass them to other functions easily:

把函数当作程序中的变量,这样你就可以很容易地将它们传递给其他函数:

def test ():
   print "test was invoked"

def invoker(func):
   func()

invoker(test)  # prints test was invoked

#3


8  

A function name can become a variable name (and thus be passed as an argument) by dropping the parentheses. A variable name can become a function name by adding the parentheses.

通过删除括号,函数名可以成为变量名(因此作为参数传递)。通过添加括号,变量名可以成为函数名。

In your example, equate the variable rules to one of your functions, leaving off the parentheses and the mention of the argument. Then in your game() function, invoke rules( v ) with the parentheses and the v parameter.

在您的示例中,将变量规则与您的函数之一等同起来,去掉括号和参数的说明。然后在game()函数中,使用括号和v参数调用规则(v)。

if puzzle == type1:
    rules = Rule1
else:
    rules = Rule2

def Game(listA, listB, rules):
    if rules( v ) == True:
        do...
    else:
        do...

#4


7  

Just pass it in, like this:

把它传递进去,就像这样:

Game(list_a, list_b, Rule1)

and then your Game function could look something like this (still pseudocode):

然后你的游戏函数可以是这样的(仍然是伪代码)

def Game(listA, listB, rules=None):
    if rules:
        # do something useful
        # ...
        result = rules(variable) # this is how you can call your rule
    else:
        # do something useful without rules

#5


6  

A generalized approach

一个通用的方法

For passing both a function, and the parameters to the function (e.g. using the same iteration routine for different functions) consider the following (python2.x) example:

要将函数和参数传递给函数(例如,对不同的函数使用相同的迭代例程),请考虑以下示例(python2.x):

def test(a, b):
    '''The function to pass'''
    print a+b

def looper(func, **kwargs):
    '''A basic iteration function'''
    for i in range(5):
        # Our passed function with passed parameters
        func(*tuple(value for _, value in kwargs.iteritems()))

if __name__ == '__main__':
    # This will print `3` five times
    looper(test, a=1, b=2)

Some explanation

一些解释

  • tuple( i for i in (1, 2, 3)) is a tuple generator, creating a tuple from the items in a list, set, tuple... in our case, the values from **kwargs
  • tuple(我在(1、2、3)中)是一个tuple生成器,从列表中的项创建一个tuple, set、tuple…在我们的例子中,来自**kwargs的值
  • the * in front of the tuple() will unpack its contents, effectively passing them as parameters to the passed function
  • tuple()前面的*将解压它的内容,有效地将它们作为参数传递给传递的函数
  • _ in the generator is just a place holder for the key, since we aren't using that
  • 发电机里的_只是钥匙的存放位置,因为我们不用它

For python3.x:

python3.x:

  • print(a+b) instead of print a+b
  • 打印(a+b)而不是打印a+b
  • kwargs.items() instead of kwargs.iteritems()
  • kwargs.items代替kwargs.iteritems()()