简体   繁体   English

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

[英]Python - Passing a function into another function

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.我正在使用 python 解决一个谜题,根据我正在解决的谜题,我将不得不使用一组特殊的规则。 How can I pass a function into another function in 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) .这只是一个伪代码,因此不是特定的,但我得到了要编译的代码,但我需要知道如何调用函数Game以及它是否正确定义,因为规则将切换为Rule1(v)Rule2(v)

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)

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

For passing both a function, and any arguments to the function:将函数和任何参数传递给函数:

from typing import Callable    

def looper(fn: Callable, n:int, *args, **kwargs):
    """
    Call a function `n` times

    Parameters
    ----------
    fn: Callable
        Function to be called.
    n: int
        Number of times to call `func`.
    *args
        Positional arguments to be passed to `func`.
    **kwargs
        Keyword arguments to be passed to `func`.

    Example
    -------
    >>> def foo(a:Union[float, int], b:Union[float, int]):
    ...    '''The function to pass'''
    ...    print(a+b)
    >>> looper(foo, 3, 2, b=4)
    6
    6
    6       
    """
    for i in range(n):
        fn(*args, **kwargs)

Depending on what you are doing, it could make sense to define a decorator , or perhaps use functools.partial .根据您在做什么,定义一个decorator或使用functools.partial可能是有意义的。

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.在您的示例中,将变量rules等同于您的函数之一,省略括号和参数的提及。 Then in your game() function, invoke rules( v ) with the parentheses and the v parameter.然后在您的game()函数中,使用括号和v参数调用rules( v )

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

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

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

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

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