Python - Passing a function into another function

穿精又带淫゛_ 提交于 2019-11-26 07:32:54

问题


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?

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).


回答1:


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:


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:


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:

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
  • the * in front of the tuple() will unpack its contents, effectively passing them as parameters to the passed function
  • _ in the generator is just a place holder for the key, since we aren't using that

For python3.x:

  • print(a+b) instead of print a+b
  • kwargs.items() instead of kwargs.iteritems()



回答4:


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:


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...


来源:https://stackoverflow.com/questions/1349332/python-passing-a-function-into-another-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!