developer tip

Python-함수를 다른 함수로 전달

optionbox 2020. 10. 7. 07:35
반응형

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

일반화 된 접근 방식

함수와 매개 변수를 함수에 전달하려면 (예 : 다른 함수에 대해 동일한 반복 루틴 사용) 다음 ( 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)

일부 설명

  • 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()

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

참고URL : https://stackoverflow.com/questions/1349332/python-passing-a-function-into-another-function

반응형