4.7.2. 키워드 인수

Keyword Arguments


Functions can also be called using keyword arguments of the form kwarg=value. For instance, the following function:
kwarg=value의 형식을 이용하면, 함수를 키워드 인수를 사용해 불러올 수 있다.
- kwarg = keyword arguments

def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
    print("-- This parrot wouldn't", action, end=' ')
    print("if you put", voltage, "volts through it.")
    print("-- Lovely plumage, the", type)
    print("-- It's", state, "!")

accepts one required argument (voltage) and three optional arguments (state, action, and type). This function can be called in any of the following ways:
하나의 필수 인수(voltage)와 나머지 세 개의 선택적 인수들(state, action, type)을 허용해보자. 이 함수는 다음 예시의 어떤 경우라도 호출이 가능하다.

parrot(1000)                                          # 1 positional argument
parrot(voltage=1000)                                  # 1 keyword argument
parrot(voltage=1000000, action='VOOOOOM')             # 2 keyword arguments
parrot(action='VOOOOOM', voltage=1000000)             # 2 keyword arguments
parrot('a million', 'bereft of life', 'jump')         # 3 positional arguments
parrot('a thousand', state='pushing up the daisies')  # 1 positional, 1 keyword

but all the following calls would be invalid:
하지만 아래의 예시들은 모두 작동하지 않는다.

parrot()                     # required argument missing
parrot(voltage=5.0, 'dead')  # non-keyword argument after a keyword argument
parrot(110, voltage=220)     # duplicate value for the same argument
parrot(actor='John Cleese')  # unknown keyword argument

In a function call, keyword arguments must follow positional arguments. All the keyword arguments passed must match one of the arguments accepted by the function (e.g. actor is not a valid argument for the parrot function), and their order is not important. This also includes non-optional arguments (e.g. parrot(voltage=1000) is valid too). No argument may receive a value more than once. Here’s an example that fails due to this restriction:
함수를 불러낼 때, 키워드 인수는 반드시 함수를 통해 주어진 인수를 따른다. 미리 설정된 모든 키워드 인수들은 반드시 함수에 의해 받아들여진 인수 중 하나와 연결되어야 한다.(예를 들어, actorparrot함수에 허용되지 않은 인수이다.) 그리고 인수의 순서는 중요하지 않다. 이것은 비선택적 인수(예를 들어, parrot(voltage=1000)역시 적절하다.)를 포함한다. 어떤 인수도 하나 이상의 값을 받을 수 없다. 아래는 이러한 제한에 실패한 예시이다.

>>> def function(a):
...     pass
...
>>> function(0, a=0)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: function() got multiple values for keyword argument 'a'

When a final formal parameter of the form **name is present, it receives a dictionary (see Mapping Types — dict) containing all keyword arguments except for those corresponding to a formal parameter. This may be combined with a formal parameter of the form *name (described in the next subsection) which receives a tuple containing the positional arguments beyond the formal parameter list. (*name must occur before **name.) For example, if we define a function like this:
**name은 형식매개변수를 의미한다. 이 형식매개변수는 '사전'을 인수로 받는다. (Mapping Types - dict를 참고하라. 아직 연결되지 않음) 이 형식매개변수는 형식매개변수 목록을 넘어 '튜플'을 인수로 받는 형식매개변수 *name과 함께 조합할 수 있다. (*name에 대해서는 다음 장에서 알아볼 것이다.) (형식매개변수 *name은 반드시 **name 앞에 놓여야 한다.)
예를 들어, 우리는 아래와 같은 함수를 정의할 수 있다.

def cheeseshop(kind, *arguments, **keywords):
    print("-- Do you have any", kind, "?")
    print("-- I'm sorry, we're all out of", kind)
    for arg in arguments:
        print(arg)
    print("-" * 40)
    keys = sorted(keywords.keys())
    for kw in keys:
        print(kw, ":", keywords[kw])

It could be called like this:
위 함수는 이런식으로 불러올 수 있다.

cheeseshop("Limburger", "It's very runny, sir.",
           "It's really very, VERY runny, sir.",
           shopkeeper="Michael Palin",
           client="John Cleese",
           sketch="Cheese Shop Sketch")

and of course it would print:
그리고 다음과 같은 답을 내놓는다.

-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

Note that the list of keyword argument names is created by sorting the result of the keywords dictionary’s keys() method before printing its contents; if this is not done, the order in which the arguments are printed is undefined.
주목할 점 : 키워드 인수 이름 목록은 출력하기 전에 먼저 키워드 사전의 key()메소드를 정렬하여 만들어진다. 만약 이렇게 되지 않는다면 인수가 출력되는 순서가 뒤죽박죽이 된다.

참고) sorted()는 입력된 값을 정렬한 후 그 결과를 리스트로 만들어 내보낸다.

results matching ""

    No results matching ""