임의의 인수

개발자를 위한 Python 중급

Jasmin Ludolf

Curriculum Manager

정의된 인수의 한계

def average(values):
    """Find the mean in a sequence of values and round to two decimal places."""

    average_value = sum(values) / len(values)
    rounded_average = round(average_value, 2)
    return rounded_average

# Using six arguments print(average(15, 29, 4, 13, 11, 8))
TypeError: average() takes 1 positional argument but 6 were given
개발자를 위한 Python 중급

임의의 위치 인수

  • 독스트링은 사용자 정의 함수의 사용법을 명확히 하는 데 도움이 됨

  • 임의 인수로는 함수에 인수의 수가 몇 개든지 쓸 수 있음

# Allow any number of positional, non-keyword arguments
def average(*args):
    # Function code remains the same
  • 보통 사용하는 이름: *args

  • 다양한 용도로 사용할 수 있으면서도 예상했던 결과 제공!

개발자를 위한 Python 중급

임의의 위치 인수 사용하기

# Calling average with six positional arguments
print(average(15, 29, 4, 13, 11, 8))
13.33
개발자를 위한 Python 중급

Args는 단일 이터러블 생성

  • *: Convert arguments to a single iterable (tuple)
# Calculating across multiple lists
print(average(*[15, 29], *[4, 13], *[11, 8]))
13.33
개발자를 위한 Python 중급

임의의 키워드 인수

# Use arbitrary keyword arguments
def average(**kwargs):

average_value = sum(kwargs.values()) / len(kwargs.values()) rounded_average = round(average_value, 2) return rounded_average
  • 임의의 키워드 인수: **kwargs

  • keyword=value

개발자를 위한 Python 중급

임의의 키워드 인수 사용하기

# Calling average with six kwargs
print(average(a=15, b=29, c=4, d=13, e=11, f=8))
13.33
# Calling average with one kwarg
print(average(**{"a":15, "b":29, "c":4, "d":13, "e":11, "f":8}))
13.33
  • 딕셔너리의 각 키-값 쌍은 인수와 값에 매핑됨
개발자를 위한 Python 중급

Kwargs는 단일 이터러블 생성

# Calling average with three kwargs
print(average(**{"a":15, "b":29}, **{"c":4, "d":13}, **{"e":11, "f":8}))
13.33
개발자를 위한 Python 중급

연습해 봅시다!

개발자를 위한 Python 중급

Preparing Video For Download...