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)

239494 次浏览

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

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

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.

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


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

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.