요약

  • 부가적인 변수들을 함수에 사용하기 위해 args, kwargs 활용
  • args 객체는 tuple 형태, kwargs 객체는 dictionary 형태
  • 객체 부여 순서: 필수 파라미터 → args (key-value 형태 전까지) → kwargs (나머지 key-value)

1. *args 변수

def regist(name, sex, *args):
    country = args[0] if len(args) >= 1 else None
    city = args[1] if len(args) >= 2 else None
 
regist('hyun', 'male', 'korea', 'seoul')
  • args 객체는 Tuple 형태
  • 부가정보가 없는 경우 인덱싱 오류 발생 → if 조건문으로 안전 로직 추가

2. **kwargs

def some_func(**kwargs):
    name = kwargs.get('name') or ''
    country = kwargs.get('country') or ''
    print(f'name: {name}, country: {country}')
 
some_func(name='hyun', country='kr')
  • kwargs 객체는 Dictionary 형태
  • get 함수 활용 → key가 없는 경우 에러 대신 None 반환

3. args와 kwargs 함께 사용

작동 순서

  1. 필수 파라미터는 각 변수에 캡쳐
  2. key=value 형태가 나오기 전까지 args에 캡쳐
  3. key=value 형태는 kwargs에 캡쳐
def regist(name, sex, *args, **kwargs):
    print(name, sex, args, kwargs)
 
regist('hyun', 'male', 'korea', 'seoul', phone=010, email='hyun@naver.com')

참고사이트