본문 바로가기

코딩/파이썬 기초

[Python] 파이썬 튜토리얼 021. 함수 매개변수에 별표 *와 **의 혼용 (*args, **kw)

▶ 함수 매개변수에 별표 *와 **의 혼용 (*args, **kw)

python : 함수 : *args와 **kw의 혼용

 

파이썬 표준(내장) 라이브러리의 코드나 별도 파이썬 패키지(라이브러리)의 코드를 분석하다 보면 함수 또는 메서드의 매개변수에 별표 한 개(*)와 두 개(**)가 순차적으로 적용되어 있는 것을 볼 수 있다.

 

    def tk_setPalette(self, *args, **kw):
        """Set a new color scheme for all widget elements.

        A single color as argument will cause that all colors of Tk
        widget elements are derived from this.
        Alternatively several keyword parameters and its associated
        colors can be given. The following keywords are valid:
        activeBackground, foreground, selectColor,
        activeForeground, highlightBackground, selectBackground,
        background, highlightColor, selectForeground,
        disabledForeground, insertBackground, troughColor."""
        self.tk.call(('tk_setPalette',)
              + _flatten(args) + _flatten(list(kw.items())))

 

함수의 매개변수 정의에서 별표 *와 **의 혼용은 별표 *와 **를 각각 사용하는 방법과 동일하다.

단, 함수의 매개변수 정의 시 별표 *가 붙는 매개변수는 별표 **가 붙는 매개변수 앞에 위치한다.

 

# python 3.9.5

def show_scores_numbers(*scores, **numbers):
    for s in scores:
        print(s)

    print()

    for k, v in numbers.items():
        print(k, v)

show_scores_numbers(10,
                    20,
                    30,
                    40,
                    50,
                    pen=1,
                    notebook=2,
                    ink=0,
                    computer=1,
                    monitor=2)

 

위의 코드를 실행한 결과는 아래와 같다.

show_scores_numbers 함수는 전달받은 scores 및 numbers의 값을 하나씩 출력한다.

매개변수 numbers는 딕셔너리를 전달받기 때문에 items 메서드를 이용해 키와 값의 쌍을 추출한다.

 

*scores와 **numbers의 혼용

 

아래의 코드에서 처럼 매개변수 scores에 대입되어야 하는 값이 키워드=값 형식이면 오류가 발생한다.

 

# python 3.9.5

def show_scores_numbers(*scores, **numbers):
    for s in scores:
        print(s)

    print()

    for k, v in numbers.items():
        print(k, v)

show_scores_numbers(mouse=1,
                    10,
                    20,
                    30,
                    40,
                    50,
                    pen=1,
                    notebook=2,
                    ink=0,
                    computer=1,
                    monitor=2)

 

키워드=값 형식에 의한 오류

 

또한 아래의 코드에서 처럼 매개변수 numbers에 대입되어야 하는 값이 키워드=값 형식이 아니어도 오류가 발생한다.

 

# python 3.9.5

def show_scores_numbers(*scores, **numbers):
    for s in scores:
        print(s)

    print()

    for k, v in numbers.items():
        print(k, v)

show_scores_numbers(10,
                    20,
                    30,
                    40,
                    50,
                    pen=1,
                    notebook=2,
                    ink=0,
                    computer=1,
                    monitor=2,
                    100)

 

키워드=값 형식이 아닌 코드에 의한 오류