IT박스

파이썬에서 인수 목록이있는 함수 호출

itboxs 2020. 6. 17. 19:20
반응형

파이썬에서 인수 목록이있는 함수 호출


파이썬에서 다른 함수 내부의 함수를 호출하려고하는데 올바른 구문을 찾을 수 없습니다. 내가하고 싶은 것은 다음과 같습니다.

def wrapper(func, args):
    func(args)

def func1(x):
    print(x)

def func2(x, y, z):
    return x+y+z

wrapper(func1, [x])
wrapper(func2, [x, y, z])

이 경우 첫 번째 통화는 작동하고 두 번째 통화는 작동하지 않습니다. 내가 수정하고 싶은 것은 호출 된 함수가 아닌 래퍼 함수입니다.


다른 답변을 조금 확장하려면 다음을 수행하십시오.

라인에서 :

def wrapper(func, *args):

옆의 * args는 "주어진 나머지 매개 변수를 가져 와서 args" 라는 목록에 넣습니다 .

라인에서 :

    func(*args)

args여기 옆에있는 * 는 "args라고하는이 목록을 가져 와서 나머지 매개 변수로 '포장 해제"한다는 의미입니다.

따라서 다음을 수행 할 수 있습니다.

def wrapper1(func, *args): # with star
    func(*args)

def wrapper2(func, args): # without star
    func(*args)

def func2(x, y, z):
    print x+y+z

wrapper1(func2, 1, 2, 3)
wrapper2(func2, [1, 2, 3])

에서이 wrapper2목록은 명시 적으로 전달하지만, 두 래퍼에 args목록이 포함되어 있습니다 [1,2,3].


함수를 포장하는 가장 간단한 방법

    func(*args, **kwargs)

... func ()을 호출하는 래퍼를 수동으로 작성하는 것 입니다.

    def wrapper(*args, **kwargs):
        # do something before
        try:
            return func(*a, **kwargs)
        finally:
            # do something after

파이썬에서 함수는 객체이므로 다른 함수의 인수로 이름을 전달하고 반환 할 수 있습니다. anyFunc () 함수에 대한 래퍼 생성기를 작성할 수도 있습니다 .

    def wrapperGenerator(anyFunc, *args, **kwargs):
        def wrapper(*args, **kwargs):
            try:
                # do something before
                return anyFunc(*args, **kwargs)
            finally:
                #do something after
        return wrapper

파이썬에서 함수의 모든 인수에 대해 알지 못하거나 이름을 지정하지 않으려는 경우 인수의 튜플을 참조 할 수 있습니다.이 이름은 뒤에 괄호 안에 별표가 붙습니다. 함수 이름 :

    *args

예를 들어, 여러 개의 인수를 취하는 함수를 정의 할 수 있습니다.

    def testFunc(*args):
        print args    # prints the tuple of arguments

Python provides for even further manipulation on function arguments. You can allow a function to take keyword arguments. Within the function body the keyword arguments are held in a dictionary. In the parentheses after the function name this dictionary is denoted by two asterisks followed by the name of the dictionary:

    **kwargs

A similar example that prints the keyword arguments dictionary:

    def testFunc(**kwargs):
        print kwargs    # prints the dictionary of keyword arguments

You can use *args and **kwargs syntax for variable length arguments.

What do *args and **kwargs mean?

And from the official python tutorial

http://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions


The literal answer to your question (to do exactly what you asked, changing only the wrapper, not the functions or the function calls) is simply to alter the line

func(args)

to read

func(*args)

This tells Python to take the list given (in this case, args) and pass its contents to the function as positional arguments.

This trick works on both "sides" of the function call, so a function defined like this:

def func2(*args):
    return sum(args)

would be able to accept as many positional arguments as you throw at it, and place them all into a list called args.

I hope this helps to clarify things a little. Note that this is all possible with dicts/keyword arguments as well, using ** instead of *.


You need to use arguments unpacking..

def wrapper(func, *args):
    func(*args)

def func1(x):
    print(x)

def func2(x, y, z):
    print x+y+z

wrapper(func1, 1)
wrapper(func2, 1, 2, 3)

A small addition to previous answers, since I couldn't find a solution for a problem, which is not worth opening a new question, but led me here.

Here is a small code snippet, which combines lists, zip() and *args, to provide a wrapper that can deal with an unknown amount of functions with an unknown amount of arguments.

def f1(var1, var2, var3):
    print(var1+var2+var3)

def f2(var1, var2):
    print(var1*var2)

def f3():
    print('f3, empty')

def wrapper(a,b, func_list, arg_list):
    print(a)
    for f,var in zip(func_list,arg_list):
        f(*var)
    print(b)

f_list = [f1, f2, f3]
a_list = [[1,2,3], [4,5], []]

wrapper('begin', 'end', f_list, a_list)

Keep in mind, that zip() does not provide a safety check for lists of unequal length, see zip iterators asserting for equal length in python.

참고URL : https://stackoverflow.com/questions/817087/call-a-function-with-argument-list-in-python

반응형