4.7.1. 기본적인 인수의 값

Default Argument Values


The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:
가장 유용한 형태는 하나 또는 그 이상의 인수에 기본(default) 값을 지정해 두는 것이다. 이 형태는 허용된 것보다 더 적은 인수를 이용해 함수를 호출할 수 있는 함수를 만든다.

def ask_ok(prompt, retries=4, reminder='Please try again!'):
    while True:
        ok = input(prompt)
        if ok in ('y', 'ye', 'yes'):
            return True
        if ok in ('n', 'no', 'nop', 'nope'):
            return False
        retries = retries - 1
        if retries < 0:
            raise ValueError('invalid user response')
        print(reminder)

This function can be called in several ways:
이 함수는 세가지 방식으로 호출될 수 있다.

  • giving only the mandatory argument:
    ask_ok('Do you really want to quit?')
    • 필수 인수만 제공하는 방식
  • giving one of the optional arguments: ask_ok('OK to overwrite the file?', 2)
    • 선택 가능한 인수 중 하나를 제공하는 방식
  • or even giving all arguments: ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')
    • 모든 인수를 제공하는 방식

This example also introduces the in keyword. This tests whether or not a sequence contains a certain value.
이 예시는 in키워드 역시 도입한다. in은 시퀀스가 특정 값을 가지고 있는지 테스트하는 기능을 한다.

The default values are evaluated at the point of function definition in the defining scope, so that
이 기본값들은 함수를 정의하는 시점에 정의된 범위 안에서 평가된다. 따라서...

i = 5

def f(arg=i):
    print(arg)

i = 6
f()

위 예시의 f()5를 출력한다.

Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls:
중요한 경고사항 : 기본 값은 단 한 번 평가된다. 이 특성은 기본값이 리스트, 사전, 또는 대부분의 클래스 인스턴스들과 같은 가변객체일 때 차이를 만든다. 예를 들어, 다음 예시에서 함수는 그것에게 전달된 인수를 다음 번 호출 위에 쌓아올린다.(축적한다.)

def f(a, L=[]):
    L.append(a)
    return L

print(f(1))
print(f(2))
print(f(3))

위 예시는 다음과 같은 출력을 내놓는다.

[1]
[1, 2]
[1, 2, 3]

If you don’t want the default to be shared between subsequent calls, you can write the function like this instead:
함수를 연속해서 호출할 때 기본 값이 공유되는 것이 싫다면, 다음과 같이 함수를 설정해야 한다.

def f(a, L=None):
    if L is None:
        L = []
    L.append(a)
    return L

results matching ""

    No results matching ""