argument / keyword-argument unpacking parameters

sycho·2023년 9월 26일
0

cs-tips

목록 보기
6/15

argument unpacking parameters

우리가 foo를 다음과 같이 정의했다고 해보자.

# Excess positional argument (python 2) example:
def foo(a, b, c, *args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

이렇게 정의하면 다음과 같이 호출하면

foo("test_a", "test_b", "test_c", "excess1", "excess2")

뒤의 '위치'상 과도한 개수의 parameter들은 args에 들어가게 할 수 있다. 이때 args의 type은 tuple이며, 만약 초과된 parameter이 없으면 empty tuple이 된다.

("excess1", "excess2")

keyword argument unpacking parameters

우리가 foo를 다음과 같이 정의했다고 해보자.

# Excess keyword argument (python 2) example:
def foo(a, b, c, **kwargs):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

이렇게 정의하면 다음과 같이 호출하면

foo(a="test_a", d="excess1", c="test_c", b="test_b", k="excess2")

존재하는 parameter 이외의 녀석들이 발견된 경우 이것들을 args에 들어가게 할 수 있다. 이때 args의 type은 dictionary이고, dictionary의 key는 기존에 존재하지 않던 이름들 그 자체가 된다. 위의 경우 dk가 되겠죠.

{d="excess1", k="excess2"}

만약 초과된 parameter이 없으면 empty dictionary가 된다.

Using both

이걸 혼용해서 쓰는 경우도 있다.

def foo(*args, **kwargs):
	for arg in args:
    	print(arg)
    for arg in kwargs:
    	print(arg)

다음과 같이 호출한다면

foo(1, 2, a="test_a", b="test_b")

args(1, 2)가, kwargs에는 {a = "test_a", b = "test_b}가 저장이 된다.

profile
CS 학부생, 핵심 관심 분야 : Embed/System/Architecture/SWE

0개의 댓글