TIL no.23 - Python - 4. variable arguments

박준규·2019년 10월 12일
0

Python

목록 보기
4/15

python에서 variable arguments는 두 종류가 있습니다.
1. Keyworded variable length of arguments
2. Non-keyworded variable length of arguments


1. Keyworded variable length of arguments

Keyworded arguments를 0~N개로 유동적으로 받을 수 있는 것을 뜻합니다.

parameter 이름앞에 두개의 별표 (**) 로 시작해야 합니다.

**parameters


가장 중요한 점은
Keyworded variable length of arguments는 dictionary 형태로 지정된다는 것입니다.


Keyworded variable length of arguments를 이용한 함수로 예를 들겠습니다.

def buy_A_car(**kwargs):
    print(f"다음 사양의 자동차를 구입하십니다:")
    for key in kwargs:
        print(f"{key} : {kwargs[key]}")
        
        #여기서 key는 "내"가 아무 이름이나 선언해주면 됩니다.
        #저는 kwargs가 dictionary로 지정된다는 느낌을 확실히 표현하기 위해
        #key라는 이름으로 선언했습니다.

이를 호출할때, 다음과 같이 호출 할 수 있습니다.

buy_A_car(seat="가죽", blackbox="최신", tint="yes")

그러면 kwargs 파라미터는 다음과 같은 dictionary로 함수에 전해지게 됩니다.
{'seat': '가죽', 'blackbox': '최신', 'tint': 'yes'}

이를 그림으로 표현하면 다음과 같습니다.


2. Non-keyworded variable length of arguments

on-keyworded variable length of arguments 혹은 그냥 variable length of arguments 라고 합니다. 더 간단하게 variable arguments 라고 하기도 합니다.

parameter 이름앞에 한개의 별표 (*) 로 시작해야 합니다.

*parameters


가장 중요한 점은
Non-keyworded variable length of arguments는 tuple 형태로 지정된다는 것입니다.


3. Mixing args and kwargs

Variable arguments와 keyworded variable arguments 둘다 사용하여 함수를 정의할 수 도 있습니다.

def do_something(*args, **kwargs):
     ## some code here...
     ....

왜 둘다 사용할까요?
둘다 사용하면 어떠한 형태와 수의 argument도 허용 가능한 함수가 됩니다.
즉, 모든 인자를 허용하는 함수이고 parameter에 있어서 굉장히 유동적인 함수가 되는 것입니다.

do_something(1, 2, 3, name="정우성", age=45)
do_something(1, 2, 3, 4, 5, "hello", {"주소" : "서울", "국가" : "한국"})
do_something(name="정우성", gender="남", height="187")
do_something(1)
do_something()
profile
devzunky@gmail.com

0개의 댓글