[python] 위치 인자 모으기(*arg)와 키워드 인자 모으기(**kwargs)

위치 인자 모으기 (*args)

함수의 매개변수에 *을 사용할 때, 이 *은 매개변수에서 위치 인자 변수들을 튜플로 묶어줍니다.

def (*args):
... print('Positional argument tuple:', args)

위 함수를 아래처럼 인자 없이 불러오면 *args에는 아무것도 들어 있지 않습니다.

what_is_args()
Positional argument tuple: ()

이번에는 인자를 넣어서 args 튜플을 출력해 보겠습니다.

what_is_args(1, 2, 3, 'data', 'science')
Positional argument tuple: (1, 2, 3, 'data', 'science')

print() 와 같은 함수는 위치 인자를 지정할 때 맨 끝에 *args를 써서 나머지 인자를 모두 취하게 할 수 있습니다.

def printmore(required1, required2, *args):
... print('need this:', required1)
... print('need this too:', required2)
... print('all the rest:', args)
printmore('pen', 'paper', 'watch', 'ipad', 'camera')
need this: pen
need this too: paper
all the rest: ('watch', 'ipad', 'camera')

키워드 인자 모으기 (**kwargs)

키워드 인자를 딕셔너리로 묶기 위해 **를 사용할 수 있습니다. 인자의 이름은 키고, 값은 이 키에 대응하는 딕셔너리 값입니다. 다음 예는 print_kwargs() 함수를 정의해 키워드 인자를 출력합니다.

>>> def print_kwargs(**kwargs):
... print('Keyword arguments:', kwargs)

키워드 인자를 넣어서 함수를 호출해보겠습니다.

>>> def print_kwargs(**kwargs):
... print('Keyword arguments:', kwargs)

>>> print_kwargs(computer='macbook', tablet='ipad', watch='applewatch')
Keyword arguments: {'computer': 'macbook', 'tablet': 'ipad', 'watch': 'applewatch'}

*이 포스트는 Introducing Python
을 보고 연습한 내용을 정리한 것입니다.