Python에서는 가변 인자와 언패킹을 활용해 더 유연하고 효율적인 코드를 작성할 수 있습니다. 이 글에서는 *와 **의 역할, 네임드 튜플(namedtuple), 언패킹(unpacking), 그리고 가변 인자 사용법을 정리합니다.
namedtuple)namedtuple은 일반 튜플과 비슷하지만, 필드 이름으로 접근할 수 있는 데이터 구조입니다.
from collections import namedtuple
# Triangle 네임드 튜플 정의
Tri = namedtuple('Triangle', ['width', 'height'])
t = Tri(3, 7)
# 인덱스로 접근
print(t[0], t[1]) # 출력: 3 7
# 필드 이름으로 접근
print(t.width, t.height) # 출력: 3 7
# Circle 네임드 튜플 정의
Circle = namedtuple('Circle', ['radius'])
circle = Circle(10)
print(circle[0]) # 출력: 10
print(circle.radius) # 출력: 10
*, **)의 사용언패킹은 iterable(리스트, 튜플 등) 또는 dictionary를 풀어서 함수에 전달할 때 사용합니다.
*로 iterable 전달def who(a, b, c):
print(a, b, c, sep=",")
# 딕셔너리 정의
d = dict(a=1, b=2, c=3)
# 키만 언패킹 (d의 key만 전달)
who(*d) # 출력: a,b,c
**로 dictionary 전달# 값(value)을 언패킹
who(**d) # 출력: 1,2,3
# 딕셔너리의 key와 value 출력
for k, v in d.items(): # [('a', 1), ('b', 2), ('c', 3)]
print(k, v)
# 키와 값을 함께 언패킹 (오류 발생)
who(*(d.items())) # 키와 값을 함께 넘길 수 없음
*args, **kwargsPython에서는 가변 인자를 받을 수 있도록 *args와 **kwargs를 활용합니다.
*args: 튜플로 묶어서 받기def func(*args): # 인자를 튜플로 묶음
print(args)
func() # 출력: ()
func(1) # 출력: (1,)
func(1, 2, 3) # 출력: (1, 2, 3)
**kwargs: 딕셔너리로 묶어서 받기def func(**kwargs): # 인자를 딕셔너리로 묶음
print(kwargs)
func(a=1) # 출력: {'a': 1}
func(a=1, b=2) # 출력: {'a': 1, 'b': 2}
func(a=1, b=2, c=3) # 출력: {'a': 1, 'b': 2, 'c': 3}
*args와 **kwargs를 동시에 사용def func(*args, **kwargs):
print("args:", args) # 튜플로 출력
print("kwargs:", kwargs) # 딕셔너리로 출력
func(1, 2, 3, a=4, b=5)
# 출력:
# args: (1, 2, 3)
# kwargs: {'a': 4, 'b': 5}
t = (1,)
print(t) # 출력: (1,)
a, *b, c = 1, 2, 3, 4
print(a) # 출력: 1
print(b) # 출력: [2, 3]
print(c) # 출력: 4
namedtuple: 필드 이름으로 데이터에 접근 가능.*args, **kwargs: 가변 인자를 함수에 전달하는 방법.*, **: iterable과 dictionary를 언패킹하여 함수 호출 시 활용.