繁体   English   中英

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

[英]Python - Passing a function into another function

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

例子

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

这只是一个伪代码,因此不是特定的,但我得到了要编译的代码,但我需要知道如何调用函数Game以及它是否正确定义,因为规则将切换为Rule1(v)Rule2(v)

只需像任何其他参数一样传入它:

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

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

print b(a,10)

将函数视为程序中的变量,以便您可以轻松地将它们传递给其他函数:

def test ():
   print "test was invoked"

def invoker(func):
   func()

invoker(test)  # prints test was invoked

将函数和任何参数传递给函数:

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)

根据您在做什么,定义一个decorator或使用functools.partial可能是有意义的。

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

在您的示例中,将变量rules等同于您的函数之一,省略括号和参数的提及。 然后在您的game()函数中,使用括号和v参数调用rules( v )

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

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

只需传入它,就像这样:

Game(list_a, list_b, Rule1)

然后你的游戏函数可能看起来像这样(仍然是伪代码):

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