[Python] *Args와 **Kwags가 뭘까?

김예신·2022년 6월 19일
0

🤔


함수 정의들을 보다보면 *혹은 **이 붙은 위와 같은 함수 설명들을 볼 수가 있다.
제대로 짚고 넘어가지 않아 헷갈리던 개념을 제대로 짚고 넘어간다.

Argument

*arg → 여러개의 argument를 '튜플'로 처리한다.
변수명이 꼭 arg여야 하는것은 아니고 원하는 매개변수를 앞에 *을 붙여준다.

def printuple(*Something):
    print(f"Name: {Something}")
    print(f"Type: {type(Something)}")

>>> printuple("안녕", "하세요", "저는", "김예신", "입니다.")

Name: ('안녕', '하세요', '저는', '김예신', '입니다.')
Type: <class 'tuple'>

Key Word argument

**Kwag → keyword=‘value’로 입력할 경우에
keyword와 ‘value‘를 각 키와 아이템으로 가진 ‘딕셔너리'로 처리한다.

def printdict(**Something):
    print(f"Items: {Something.items()}")
    print(f"Keys: {Something.keys()}")
    print(f"Values: {Something.values()}")
    print(f"Type: {type(Something)}")
    print(Something)

>>> printdict(yesin=2, hi=1, thanks=3, thanku=2)

Items: dict_items([('yesin', 2), ('hi', 1), ('thanks', 3), ('thanku', 2)])
Keys: dict_keys(['yesin', 'hi', 'thanks', 'thanku'])
Values: dict_values([2, 1, 3, 2])
Type: <class 'dict'>
{'yesin': 2, 'hi': 1, 'thanks': 3, 'thanku': 2}
profile
life is dancing

0개의 댓글