가변 개수의 인수 처리하기
Python 함수는 가변적인 개수의 인수를 받도록 설계될 수 있습니다. 이는 함수에 전달될 인수의 개수를 미리 알 수 없을 때 유용합니다.
가변 위치 인수 (*args)
매개변수 이름 앞에 별표 (*) 를 붙이면, 임의의 개수의 위치 인수를 튜플 (tuple) 로 모을 수 있습니다. args라는 이름은 관례이지만, 유효한 다른 매개변수 이름을 사용할 수도 있습니다.
가변 키워드 인수 (**kwargs)
매개변수 이름 앞에 별표 두 개 (**) 를 붙이면, 임의의 개수의 키워드 인수를 딕셔너리 (dictionary) 로 모을 수 있습니다. kwargs라는 이름 역시 관례입니다.
이 개념들을 결합해 보겠습니다. variable_args.py 파일을 열고 다음 코드를 추가하십시오:
## *args 를 사용하여 가변 개수의 숫자를 합산
def calculate_sum(*numbers):
print(f"Arguments received as a tuple: {numbers}")
total = sum(numbers)
print(f"Sum: {total}\n")
## **kwargs 를 사용하여 추가 프로필 정보를 캡처
def person_profile(name, age, **other_info):
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Other Info: {other_info}\n")
## 함수 호출
calculate_sum(1, 2, 3)
calculate_sum(10, 20, 30, 40, 50)
person_profile('Wang Wu', 26, gender="Male", job="Writer")
person_profile('Zhao Liu', 28, city="Beijing", status="Active")
터미널에서 스크립트를 실행하십시오:
python3 ~/project/variable_args.py
출력 결과는 numbers가 튜플이고 other_info가 딕셔너리임을 보여줍니다:
Arguments received as a tuple: (1, 2, 3)
Sum: 6
Arguments received as a tuple: (10, 20, 30, 40, 50)
Sum: 150
Name: Wang Wu
Age: 26
Other Info: {'gender': 'Male', 'job': 'Writer'}
Name: Zhao Liu
Age: 28
Other Info: {'city': 'Beijing', 'status': 'Active'}