3. 데이터 모델
**************


3.1. 객체, 값, 형
=================

*객체 (Objects)*는 파이썬이 데이터(data)를 추상화한 것(abstraction)입
니다. 파이썬 프로그램의 모든 데이터는 객체나 객체 간의 관계로 표현됩니
다. (폰 노이만(Von Neumann)의 "프로그램 내장식 컴퓨터(stored program
computer)" 모델을 따르고, 또 그 관점에서 코드 역시 객체로 표현됩니다.)

Every object has an identity, a type and a value.  An object's
*identity* never changes once it has been created; you may think of it
as the object's address in memory.  The "is" operator compares the
identity of two objects; the "id()" function returns an integer
representing its identity.

CPython 의 경우, "id(x)" 는 "x" 가 저장된 메모리의 주소입니다.

객체의 형은 객체가 지원하는 연산들을 정의하고 (예를 들어, "길이를 갖고
있나?") 그 형의 객체들이 가질 수 있는 가능한 값들을 정의합니다.
"type()" 함수는 객체의 형(이것 역시 객체다)을 돌려줍니다. 아이덴티티와
마찬가지로, 객체의 *형 (type)* 역시 변경되지 않습니다. [1]

어떤 객체들의 *값* 은 변경할 수 있습니다. 값을 변경할 수 있는 객체들을
*가변(mutable)* 이라고 합니다. 일단 만들어진 후에 값을 변경할 수 없는
객체들을 *불변(immutable)* 이라고 합니다. (가변 객체에 대한 참조를 저
장하고 있는 불변 컨테이너의 값은 가변 객체의 값이 변할 때 변경된다고
볼 수도 있습니다; 하지만 저장하고 있는 객체들의 집합이 바뀔 수 없으므
로 컨테이너는 여전히 불변이라고 여겨집니다. 따라서 불변성은 엄밀하게는
변경 불가능한 값을 갖는 것과는 다릅니다. 좀 더 미묘합니다.) 객체의 가
변성(mutability)은 그것의 형에 의해 결정됩니다; 예를 들어 숫자, 문자열
, 튜플(tuple)은 불변이지만, 딕셔너리(dictionary) 와 리스트(list)는 가
변입니다.

객체는 결코 명시적으로 파괴되지 않습니다; 더 참조되지 않을 때
(unreachable) 가비지 수거(garbage collect)됩니다. 구현이 가비지 수거를
지연시키거나 아예 생략하는 것이 허락됩니다 --- 아직 참조되는 객체들을
수거하지 않는 이상 가비지 수거가 어떤 식으로 구현되는지는 구현의 품질
문제입니다.

CPython 은 현재 참조 횟수 계산(reference-counting) 방식을 사용하는데,
(선택 사항으로) 순환적으로 연결된 가비지의 지연된 감지가 추가됩니다.
이 방법으로 대부분 객체를 참조가 제거되자마자 수거할 수 있습니다. 하지
만 순환 참조가 있는 가비지들을 수거한다는 보장은 없습니다. 순환적 가비
지 수거의 제어에 관한 정보는 "gc" 모듈 문서를 참조하면 됩니다. 다른 구
현들은 다른 식으로 동작하고, CPython 도 변경될 수 있습니다. 참조가 제
거될 때 즉각적으로 파이널리제이션(finalization)되는 것에 의존하지 말아
야 합니다 (그래서 항상 파일을 명시적으로 닫아주어야 합니다).

Note that the use of the implementation's tracing or debugging
facilities may keep objects alive that would normally be collectable.
Also note that catching an exception with a "try"..."except" statement
may keep objects alive.

Some objects contain references to "external" resources such as open
files or windows.  It is understood that these resources are freed
when the object is garbage-collected, but since garbage collection is
not guaranteed to happen, such objects also provide an explicit way to
release the external resource, usually a "close()" method. Programs
are strongly recommended to explicitly close such objects.  The
"try"..."finally" statement and the "with" statement provide
convenient ways to do this.

어떤 객체들은 다른 객체에 대한 참조를 포함하고 있습니다. 이런 것들을 *
컨테이너(container)* 라고 부릅니다. 튜플, 리스트, 딕셔너리등이 컨테이
너의 예입니다. 이 참조들은 컨테이너의 값의 일부입니다. 대부분은, 우리
가 컨테이너의 값을 논할 때는, 들어있는 객체들의 아이덴티티 보다는 값을
따집니다. 하지만, 컨테이너의 가변성에 대해 논할 때는 직접 가진 객체들
의 아이덴티티만을 따집니다. 그래서, (튜플 같은) 불변 컨테이너가 가변
객체로의 참조를 하고 있다면, 그 가변 객체가 변경되면 컨테이너의 값도
변경됩니다.

Types affect almost all aspects of object behavior.  Even the
importance of object identity is affected in some sense: for immutable
types, operations that compute new values may actually return a
reference to any existing object with the same type and value, while
for mutable objects this is not allowed. For example, after "a = 1; b
= 1", *a* and *b* may or may not refer to the same object with the
value one, depending on the implementation. This is because "int" is
an immutable type, so the reference to "1" can be reused. This
behaviour depends on the implementation used, so should not be relied
upon, but is something to be aware of when making use of object
identity tests. However, after "c = []; d = []", *c* and *d* are
guaranteed to refer to two different, unique, newly created empty
lists. (Note that "e = f = []" assigns the *same* object to both *e*
and *f*.)


3.2. 표준형 계층
================

아래에 파이썬에 내장된 형들의 목록이 있습니다. (구현에 따라 C 나 자바
나 다른 언어로 작성된) 확장 모듈들은 추가의 형을 정의할 수 있습니다.
파이썬의 미래 버전 역시 형 계층에 형을 더할 수 있는데 (예를 들어, 유리
수, 효율적으로 저장된 정수 배열 등등), 표준 라이브러리를 통해 추가될
가능성이 더 크기는 합니다.

아래에 나오는 몇몇 형에 대한 설명은 '특수 어트리뷰트(special
attribute)' 를 나열하는 문단을 포함합니다. 이것들은 구현에 접근할 방법
을 제공하는데, 일반적인 사용을 위한 것이 아닙니다. 정의는 앞으로 변경
될 수 있습니다.


3.2.1. None
-----------

이 형은 하나의 값만을 갖습니다. 이 값을 갖는 하나의 객체가 존재합니다.
이 객체에는 내장된 이름 "None" 을 통해 접근합니다. 여러 가지 상황에서
값의 부재를 알리는 데 사용됩니다. 예를 들어, 명시적으로 뭔가를 돌려주
지 않는 함수의 반환 값입니다. 논리값은 거짓입니다.


3.2.2. NotImplemented
---------------------

This type has a single value.  There is a single object with this
value. This object is accessed through the built-in name
"NotImplemented". Numeric methods and rich comparison methods should
return this value if they do not implement the operation for the
operands provided.  (The interpreter will then try the reflected
operation, or some other fallback, depending on the operator.)  It
should not be evaluated in a boolean context.

더 자세한 내용은 산술 연산 구현 을 참고하십시오.

버전 3.9에서 변경: Evaluating "NotImplemented" in a boolean context
was deprecated.

버전 3.14에서 변경: Evaluating "NotImplemented" in a boolean context
now raises a "TypeError". It previously evaluated to "True" and
emitted a "DeprecationWarning" since Python 3.9.


3.2.3. Ellipsis
---------------

이 형은 하나의 값만을 갖습니다. 이 값을 갖는 하나의 객체가 존재합니다.
이 객체에는 리터럴 "..." 이나 내장된 이름 "Ellipsis" 을 통해 접근합니
다. 논리값은 참입니다.


3.2.4. "numbers.Number"
-----------------------

이것들은 숫자 리터럴에 의해 만들어지고, 산술 연산과 내장 산술 함수들이
결과로 돌려줍니다. 숫자 객체는 불변입니다; 한 번 값이 만들어지면 절대
변하지 않습니다. 파이썬의 숫자는 당연히 수학적인 숫자들과 밀접하게 관
련되어 있습니다, 하지만 컴퓨터의 숫자 표현상의 제약을 받고 있습니다.

The string representations of the numeric classes, computed by
"__repr__()" and "__str__()", have the following properties:

* 클래스 생성자에 전달될 때 원래 숫자 값을 가진 객체를 생성하는 유효한
  숫자 리터럴 입니다.

* 가능하면, 표현은 10진법입니다.

* 소수점 앞의 단일 0을 제외하고, 선행 0은 표시되지 않습니다.

* 소수점 뒤의 단일 0을 제외하고, 후행 0은 표시되지 않습니다.

* 부호는 숫자가 음수일 때만 표시됩니다.

Python distinguishes between integers, floating-point numbers, and
complex numbers:


3.2.4.1. "numbers.Integral"
~~~~~~~~~~~~~~~~~~~~~~~~~~~

이것들은 수학적인 정수 집합(양과 음)에 속하는 요소들을 나타냅니다.

참고:

  정수 표현 규칙은 음수가 포함된 시프트와 마스크 연산에 가장 의미 있는
  해석을 제공하기 위한 것입니다.

두 가지 종류의 정수가 있습니다:

정수 ("int")
   이것은 (가상) 메모리가 허락하는 한, 제약 없는 범위의 숫자를 표현합
   니다. 시프트(shift)와 마스크(mask) 연산이 목적일 때는 이진 표현이
   가정되고, 음수는 일종의 2의 보수(2's complement)로 표현되는데, 부호
   비트가 왼쪽으로 무한히 확장된 것과 같은 효과를 줍니다.

불린 ("bool")
   이것은 논리값 거짓과 참을 나타냅니다. "False" 와 "True" 두 객체만
   불린 형 객체입니다. 불린 형은 int 형의 자식형(subtype)이고, 대부분
   상황에서 각기 0과1처럼 동작합니다. 예외는 문자열로 변환되는 경우인
   데, 각기 문자열 ""False"" 와 ""True"" 가 반환됩니다.


3.2.4.2. "numbers.Real" ("float")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

These represent machine-level double precision floating-point numbers.
You are at the mercy of the underlying machine architecture (and C or
Java implementation) for the accepted range and handling of overflow.
Python does not support single-precision floating-point numbers; the
savings in processor and memory usage that are usually the reason for
using these are dwarfed by the overhead of using objects in Python, so
there is no reason to complicate the language with two kinds of
floating-point numbers.


3.2.4.3. "numbers.Complex" ("complex")
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

These represent complex numbers as a pair of machine-level double
precision floating-point numbers.  The same caveats apply as for
floating-point numbers. The real and imaginary parts of a complex
number "z" can be retrieved through the read-only attributes "z.real"
and "z.imag".


3.2.5. 시퀀스들
---------------

These represent finite ordered sets indexed by non-negative numbers.
The built-in function "len()" returns the number of items of a
sequence. When the length of a sequence is *n*, the index set contains
the numbers 0, 1, ..., *n*-1.  Item *i* of sequence *a* is selected by
"a[i]". Some sequences, including built-in sequences, interpret
negative subscripts by adding the sequence length. For example,
"a[-2]" equals "a[n-2]", the second to last item of sequence a with
length "n".

Sequences also support slicing: "a[i:j]" selects all items with index
*k* such that *i* "<=" *k* "<" *j*.  When used as an expression, a
slice is a sequence of the same type. The comment above about negative
indexes also applies to negative slice positions.

어떤 시퀀스는 세 번째 "스텝(step)" 매개변수를 사용하는 "확장 슬라이싱
(extended slicing)"도 지원합니다: "a[i:j:k]" 는 "x = i + n*k", *n*
">=" "0", *i* "<=" *x* "<" *j* 를 만족하는 모든 항목 *x* 를 선택합니다
.

시퀀스는 불변성에 따라 구분됩니다


3.2.5.1. 불변 시퀀스
~~~~~~~~~~~~~~~~~~~~

불변 시퀀스 형의 객체는 일단 만들어진 후에는 변경될 수 없습니다. (만약
다른 객체로의 참조를 포함하면, 그 객체는 가변일 수 있고, 변경될 수 있
습니다; 하지만, 불변 객체로부터 참조되는 객체의 집합 자체는 변경될 수
없습니다.)

다음과 같은 형들은 불변 시퀀스입니다:

문자열(Strings)
   A string is a sequence of values that represent Unicode code
   points. All the code points in the range "U+0000 - U+10FFFF" can be
   represented in a string.  Python doesn't have a char type; instead,
   every code point in the string is represented as a string object
   with length "1".  The built-in function "ord()" converts a code
   point from its string form to an integer in the range "0 - 10FFFF";
   "chr()" converts an integer in the range "0 - 10FFFF" to the
   corresponding length "1" string object. "str.encode()" can be used
   to convert a "str" to "bytes" using the given text encoding, and
   "bytes.decode()" can be used to achieve the opposite.

튜플(Tuples)
   튜플의 항목은 임의의 파이썬 객체입니다. 두 개 이상의 항목으로 구성
   되는 튜플은 콤마로 분리된 표현식의 목록으로 만들 수 있습니다. 하나
   의 항목으로 구성된 튜플(싱글턴,singleton)은 표현식에 콤마를 붙여서
   만들 수 있습니다(괄호로 표현식을 묶을 수 있으므로, 표현식 만으로는
   튜플을 만들지 않습니다). 빈 튜플은 한 쌍의 빈 괄호로 만들 수 있습니
   다.

바이트열(Bytes)
   A bytes object is an immutable array.  The items are 8-bit bytes,
   represented by integers in the range 0 <= x < 256.  Bytes literals
   (like "b'abc'") and the built-in "bytes()" constructor can be used
   to create bytes objects.  Also, bytes objects can be decoded to
   strings via the "decode()" method.


3.2.5.2. 가변 시퀀스
~~~~~~~~~~~~~~~~~~~~

가변 시퀀스는 만들어진 후에 변경될 수 있습니다. 서브스크립션
(subscription)과 슬라이싱은 대입문과 "del" (삭제) 문의 대상으로 사용될
수 있습니다.

참고:

  The "collections" and "array" module provide additional examples of
  mutable sequence types.

현재 두 개의 내장 가변 시퀀스형이 있습니다:

리스트(Lists)
   리스트의 항목은 임의의 파이썬 객체입니다. 리스트는 콤마로 분리된 표
   현식을 대괄호 안에 넣어서 만들 수 있습니다. (길이 0이나 1의 리스트
   를 만드는데 별도의 규칙이 필요 없습니다.)

바이트 배열(Byte Arrays)
   바이트 배열(bytearray) 객체는 가변 배열입니다. 내장 "bytearray()"
   생성자로 만들어집니다. 가변이라는 것(그래서 해싱 불가능하다는 것)을
   제외하고, 바이트 배열은 불변 바이트열( "bytes") 객체와 같은 인터페
   이스와 기능을 제공합니다.


3.2.6. 집합 형들(Set types)
---------------------------

이것들은 중복 없는 불변 객체들의 순서 없고 유한한 집합을 나타냅니다.
인덱싱할 수 없습니다. 하지만 이터레이트할 수 있고, 내장 함수 "len()"
은 집합 안에 있는 항목들의 개수를 돌려줍니다. 집합의 일반적인 용도는
빠른 멤버십 검사(fast membership testing), 시퀀스에서 중복된 항목 제거
, 교집합(intersection), 합집합(union), 차집합(difference), 대칭차집합
(symmetric difference)과 같은 집합 연산을 계산하는 것입니다.

집합의 원소들에는 딕셔너리 키와 같은 불변성 규칙이 적용됩니다. 숫자 형
의 경우는 숫자 비교에 관한 일반 원칙이 적용된다는 점에 주의해야 합니다
: 만약 두 숫자가 같다고 비교되면(예를 들어, "1" 과 "1.0"), 그중 하나만
집합에 들어갈 수 있습니다.

현재 두 개의 내장 집합 형이 있습니다:

집합(Sets)
   These represent a mutable set. They are created by the built-in
   "set()" constructor and can be modified afterwards by several
   methods, such as "add".

불변 집합(Frozen sets)
   이것들은 불변 집합을 나타냅니다. 내장 "frozenset()" 생성자로 만들
   수 있습니다. 불변 집합(frozenset)은 불변이고 *해시 가능* 하므로, 다
   른 집합의 원소나, 딕셔너리의 키로 사용될 수 있습니다.


3.2.7. 매핑(Mappings)
---------------------

이것들은 임의의 인덱스 집합으로 인덱싱되는 객체들의 유한한 집합을 나타
냅니다. 인덱스 표기법(subscript notation) "a[k]" 는 매핑 "a" 에서 "k"
로 인덱스 되는 항목을 선택합니다; 이것은 표현식에 사용될 수도 있고, 대
입이나 "del" 문장의 대상이 될 수도 있습니다. 내장 함수 "len()" 은 매핑
에 포함된 항목들의 개수를 돌려줍니다.

현재 한 개의 내장 매핑 형이 있습니다:


3.2.7.1. 딕셔너리(Dictionaries)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

이것들은 거의 임의의 인덱스 집합으로 인덱싱되는 객체들의 유한한 집합을
나타냅니다. 키로 사용할 수 없는 것들은 리스트, 딕셔너리나 그 외의 가변
형 중에서 아이덴티티가 아니라 값으로 비교되는 것들뿐입니다. 딕셔너리의
효율적인 구현이, 키의 해시값이 도중에 변경되지 않고 계속 같은 값으로
유지되도록 요구하고 있기 때문입니다. 키로 사용되는 숫자 형의 경우는 숫
자 비교에 관한 일반 원칙이 적용됩니다: 만약 두 숫자가 같다고 비교되면(
예를 들어, "1" 과 "1.0"), 둘 다 같은 딕셔너리 항목을 인덱싱하는데 사용
될 수 있습니다.

딕셔너리는 삽입 순서를 유지합니다, 키가 딕셔너리에 순차적으로 추가된
순서와 같은 순서로 생성됨을 뜻합니다. 기존 키를 교체해도 순서는 변경되
지 않지만, 키를 제거했다가 다시 삽입하면 이전 위치를 유지하는 대신 끝
에 추가됩니다.

Dictionaries are mutable; they can be created by the "{}" notation
(see section 딕셔너리 디스플레이).

확장 모듈 "dbm.ndbm" 과 "dbm.gnu" 는 추가의 매핑 형을 제공하는데,
"collections" 모듈 역시 마찬가지입니다.

버전 3.7에서 변경: 딕셔너리는 3.6 이전의 파이썬 버전에서 삽입 순서를
유지하지 않았습니다. CPython 3.6에서, 삽입 순서가 유지되었지만, 그 시
점에는 언어 보증이 아니라 구현 세부 사항으로 간주하였습니다.


3.2.8. 콜러블(Callable types)
-----------------------------

이것들은 함수 호출 연산(호출 섹션 참고)이 적용될 수 있는 형들입니다:


3.2.8.1. 사용자 정의 함수
~~~~~~~~~~~~~~~~~~~~~~~~~

사용자 정의 함수 객체는 함수 정의를 통해 만들어집니다 (함수 정의 섹션
참고). 함수의 형식 매개변수(formal parameter) 목록과 같은 개수의 항목
을 포함하는 인자(argument) 목록으로 호출되어야 합니다.


3.2.8.1.1. Special read-only attributes
"""""""""""""""""""""""""""""""""""""""

+----------------------------------------------------+----------------------------------------------------+
| 어트리뷰트                                         | 의미                                               |
|====================================================|====================================================|
| function.__globals__                               | A reference to the "dictionary" that holds the     |
|                                                    | function's global variables -- the global          |
|                                                    | namespace of the module in which the function was  |
|                                                    | defined.                                           |
+----------------------------------------------------+----------------------------------------------------+
| function.__closure__                               | "None" or a "tuple" of cells that contain bindings |
|                                                    | for the names specified in the "co_freevars"       |
|                                                    | attribute of the function's "code object".  셀 객  |
|                                                    | 체는 "cell_contents" 어트리뷰트를 가지고 있습니다. |
|                                                    | 셀의 값을 읽을 뿐만 아니라 값을 설정하는 데도 사용 |
|                                                    | 할 수 있습니다.                                    |
+----------------------------------------------------+----------------------------------------------------+


3.2.8.1.2. Special writable attributes
""""""""""""""""""""""""""""""""""""""

Most of these attributes check the type of the assigned value:

+----------------------------------------------------+----------------------------------------------------+
| 어트리뷰트                                         | 의미                                               |
|====================================================|====================================================|
| function.__doc__                                   | The function's documentation string, or "None" if  |
|                                                    | unavailable.                                       |
+----------------------------------------------------+----------------------------------------------------+
| function.__name__                                  | The function's name. See also: "__name__           |
|                                                    | attributes".                                       |
+----------------------------------------------------+----------------------------------------------------+
| function.__qualname__                              | The function's *qualified name*. See also:         |
|                                                    | "__qualname__ attributes".  Added in version 3.3.  |
+----------------------------------------------------+----------------------------------------------------+
| function.__module__                                | 함수가 정의된 모듈의 이름 또는 (없는 경우) "None"  |
+----------------------------------------------------+----------------------------------------------------+
| function.__defaults__                              | A "tuple" containing default *parameter* values    |
|                                                    | for those parameters that have defaults, or "None" |
|                                                    | if no parameters have a default value.             |
+----------------------------------------------------+----------------------------------------------------+
| function.__code__                                  | The code object representing the compiled function |
|                                                    | body.                                              |
+----------------------------------------------------+----------------------------------------------------+
| function.__dict__                                  | The namespace supporting arbitrary function        |
|                                                    | attributes. See also: "__dict__ attributes".       |
+----------------------------------------------------+----------------------------------------------------+
| function.__annotations__                           | A "dictionary" containing annotations of           |
|                                                    | *parameters*. The keys of the dictionary are the   |
|                                                    | parameter names, and "'return'" for the return     |
|                                                    | annotation, if provided. See also:                 |
|                                                    | "object.__annotations__".  버전 3.14에서 변경:     |
|                                                    | Annotations are now lazily evaluated. See **PEP    |
|                                                    | 649**.                                             |
+----------------------------------------------------+----------------------------------------------------+
| function.__annotate__                              | The *annotate function* for this function, or      |
|                                                    | "None" if the function has no annotations. See     |
|                                                    | "object.__annotate__".  Added in version 3.14.     |
+----------------------------------------------------+----------------------------------------------------+
| function.__kwdefaults__                            | A "dictionary" containing defaults for keyword-    |
|                                                    | only *parameters*.                                 |
+----------------------------------------------------+----------------------------------------------------+
| function.__type_params__                           | A "tuple" containing the type parameters of a      |
|                                                    | generic function.  Added in version 3.12.          |
+----------------------------------------------------+----------------------------------------------------+

Function objects also support getting and setting arbitrary
attributes, which can be used, for example, to attach metadata to
functions.  Regular attribute dot-notation is used to get and set such
attributes.

**CPython 구현 상세:** CPython's current implementation only supports
function attributes on user-defined functions. Function attributes on
built-in functions may be supported in the future.

Additional information about a function's definition can be retrieved
from its code object (accessible via the "__code__" attribute).


3.2.8.2. 인스턴스 메서드(Instance methods)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

인스턴스 메서드는 클래스, 클래스 인스턴스와 모든 콜러블 객체 (보통 사
용자 정의 함수)을 결합합니다.

Special read-only attributes:

+----------------------------------------------------+----------------------------------------------------+
| method.__self__                                    | Refers to the class instance object to which the   |
|                                                    | method is bound                                    |
+----------------------------------------------------+----------------------------------------------------+
| method.__func__                                    | Refers to the original function object             |
+----------------------------------------------------+----------------------------------------------------+
| method.__doc__                                     | The method's documentation (same as                |
|                                                    | "method.__func__.__doc__"). A "string" if the      |
|                                                    | original function had a docstring, else "None".    |
+----------------------------------------------------+----------------------------------------------------+
| method.__name__                                    | The name of the method (same as                    |
|                                                    | "method.__func__.__name__")                        |
+----------------------------------------------------+----------------------------------------------------+
| method.__module__                                  | The name of the module the method was defined in,  |
|                                                    | or "None" if unavailable.                          |
+----------------------------------------------------+----------------------------------------------------+

Methods also support accessing (but not setting) the arbitrary
function attributes on the underlying function object.

User-defined method objects may be created when getting an attribute
of a class (perhaps via an instance of that class), if that attribute
is a user-defined function object or a "classmethod" object.

When an instance method object is created by retrieving a user-defined
function object from a class via one of its instances, its "__self__"
attribute is the instance, and the method object is said to be
*bound*.  The new method's "__func__" attribute is the original
function object.

When an instance method object is created by retrieving a
"classmethod" object from a class or instance, its "__self__"
attribute is the class itself, and its "__func__" attribute is the
function object underlying the class method.

When an instance method object is called, the underlying function
("__func__") is called, inserting the class instance ("__self__") in
front of the argument list.  For instance, when "C" is a class which
contains a definition for a function "f()", and "x" is an instance of
"C", calling "x.f(1)" is equivalent to calling "C.f(x, 1)".

When an instance method object is derived from a "classmethod" object,
the "class instance" stored in "__self__" will actually be the class
itself, so that calling either "x.f(1)" or "C.f(1)" is equivalent to
calling "f(C,1)" where "f" is the underlying function.

It is important to note that user-defined functions which are
attributes of a class instance are not converted to bound methods;
this *only* happens when the function is an attribute of the class.


3.2.8.3. 제너레이터 함수(Generator functions)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A function or method which uses the "yield" statement (see section
yield 문) is called a *generator function*.  Such a function, when
called, always returns an *iterator* object which can be used to
execute the body of the function:  calling the iterator's
"iterator.__next__()" method will cause the function to execute until
it provides a value using the "yield" statement.  When the function
executes a "return" statement or falls off the end, a "StopIteration"
exception is raised and the iterator will have reached the end of the
set of values to be returned.


3.2.8.4. 코루틴 함수(Coroutine functions)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

"async def" 를 사용해서 정의되는 함수나 메서드를 *코루틴 함수
(coroutine function)* 라고 부릅니다. 이런 함수를 호출하면 *코루틴* 객
체를 돌려줍니다. "await" 표현식을 비롯해, "async with" 와 "async for"
문을 사용할 수 있습니다. 코루틴 객체(Coroutine Objects) 섹션을 참조하
십시오.


3.2.8.5. 비동기 제너레이터 함수(Asynchronous generator functions)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A function or method which is defined using "async def" and which uses
the "yield" statement is called a *asynchronous generator function*.
Such a function, when called, returns an *asynchronous iterator*
object which can be used in an "async for" statement to execute the
body of the function.

Calling the asynchronous iterator's "aiterator.__anext__" method will
return an *awaitable* which when awaited will execute until it
provides a value using the "yield" expression.  When the function
executes an empty "return" statement or falls off the end, a
"StopAsyncIteration" exception is raised and the asynchronous iterator
will have reached the end of the set of values to be yielded.


3.2.8.6. 내장 함수(Built-in functions)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A built-in function object is a wrapper around a C function.  Examples
of built-in functions are "len()" and "math.sin()" ("math" is a
standard built-in module). The number and type of the arguments are
determined by the C function. Special read-only attributes:

* "__doc__" is the function's documentation string, or "None" if
  unavailable. See "function.__doc__".

* "__name__" is the function's name. See "function.__name__".

* "__self__" is set to "None" (but see the next item).

* "__module__" is the name of the module the function was defined in
  or "None" if unavailable. See "function.__module__".


3.2.8.7. 내장 메서드(Built-in methods)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

This is really a different disguise of a built-in function, this time
containing an object passed to the C function as an implicit extra
argument.  An example of a built-in method is "alist.append()",
assuming *alist* is a list object. In this case, the special read-only
attribute "__self__" is set to the object denoted by *alist*. (The
attribute has the same semantics as it does with "other instance
methods".)


3.2.8.8. 클래스(Classes)
~~~~~~~~~~~~~~~~~~~~~~~~

Classes are callable.  These objects normally act as factories for new
instances of themselves, but variations are possible for class types
that override "__new__()".  The arguments of the call are passed to
"__new__()" and, in the typical case, to "__init__()" to initialize
the new instance.


3.2.8.9. 클래스 인스턴스(Class Instances)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Instances of arbitrary classes can be made callable by defining a
"__call__()" method in their class.


3.2.9. 모듈(Modules)
--------------------

Modules are a basic organizational unit of Python code, and are
created by the import system as invoked either by the "import"
statement, or by calling functions such as "importlib.import_module()"
and built-in "__import__()".  A module object has a namespace
implemented by a "dictionary" object (this is the dictionary
referenced by the "__globals__" attribute of functions defined in the
module).  Attribute references are translated to lookups in this
dictionary, e.g., "m.x" is equivalent to "m.__dict__["x"]". A module
object does not contain the code object used to initialize the module
(since it isn't needed once the initialization is done).

어트리뷰트 대입은 모듈의 이름 공간 딕셔너리를 갱신합니다. 예를 들어,
"m.x = 1" 은 "m.__dict__["x"] = 1" 과 같습니다.


3.2.9.1. Import-related attributes on module objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Module objects have the following attributes that relate to the import
system. When a module is created using the machinery associated with
the import system, these attributes are filled in based on the
module's *spec*, before the *loader* executes and loads the module.

To create a module dynamically rather than using the import system,
it's recommended to use "importlib.util.module_from_spec()", which
will set the various import-controlled attributes to appropriate
values. It's also possible to use the "types.ModuleType" constructor
to create modules directly, but this technique is more error-prone, as
most attributes must be manually set on the module object after it has
been created when using this approach.

조심:

  With the exception of "__name__", it is **strongly** recommended
  that you rely on "__spec__" and its attributes instead of any of the
  other individual attributes listed in this subsection. Note that
  updating an attribute on "__spec__" will not update the
  corresponding attribute on the module itself:

     >>> import typing
     >>> typing.__name__, typing.__spec__.name
     ('typing', 'typing')
     >>> typing.__spec__.name = 'spelling'
     >>> typing.__name__, typing.__spec__.name
     ('typing', 'spelling')
     >>> typing.__name__ = 'keyboard_smashing'
     >>> typing.__name__, typing.__spec__.name
     ('keyboard_smashing', 'spelling')

module.__name__

   The name used to uniquely identify the module in the import system.
   For a directly executed module, this will be set to ""__main__"".

   This attribute must be set to the fully qualified name of the
   module. It is expected to match the value of
   "module.__spec__.name".

module.__spec__

   A record of the module's import-system-related state.

   Set to the "module spec" that was used when importing the module.
   See 모듈 스펙 for more details.

   Added in version 3.4.

module.__package__

   The *package* a module belongs to.

   If the module is top-level (that is, not a part of any specific
   package) then the attribute should be set to "''" (the empty
   string). Otherwise, it should be set to the name of the module's
   package (which can be equal to "module.__name__" if the module
   itself is a package). See **PEP 366** for further details.

   This attribute is used instead of "__name__" to calculate explicit
   relative imports for main modules. It defaults to "None" for
   modules created dynamically using the "types.ModuleType"
   constructor; use "importlib.util.module_from_spec()" instead to
   ensure the attribute is set to a "str".

   It is **strongly** recommended that you use
   "module.__spec__.parent" instead of "module.__package__".
   "__package__" is now only used as a fallback if "__spec__.parent"
   is not set, and this fallback path is deprecated.

   버전 3.4에서 변경: This attribute now defaults to "None" for
   modules created dynamically using the "types.ModuleType"
   constructor. Previously the attribute was optional.

   버전 3.6에서 변경: The value of "__package__" is expected to be the
   same as "__spec__.parent". "__package__" is now only used as a
   fallback during import resolution if "__spec__.parent" is not
   defined.

   버전 3.10에서 변경: "ImportWarning" is raised if an import
   resolution falls back to "__package__" instead of
   "__spec__.parent".

   버전 3.12에서 변경: Raise "DeprecationWarning" instead of
   "ImportWarning" when falling back to "__package__" during import
   resolution.

   Deprecated since version 3.13, will be removed in version 3.15:
   "__package__" will cease to be set or taken into consideration by
   the import system or standard library.

module.__loader__

   The *loader* object that the import machinery used to load the
   module.

   This attribute is mostly useful for introspection, but can be used
   for additional loader-specific functionality, for example getting
   data associated with a loader.

   "__loader__" defaults to "None" for modules created dynamically
   using the "types.ModuleType" constructor; use
   "importlib.util.module_from_spec()" instead to ensure the attribute
   is set to a *loader* object.

   It is **strongly** recommended that you use
   "module.__spec__.loader" instead of "module.__loader__".

   버전 3.4에서 변경: This attribute now defaults to "None" for
   modules created dynamically using the "types.ModuleType"
   constructor. Previously the attribute was optional.

   Deprecated since version 3.12, will be removed in version 3.16:
   Setting "__loader__" on a module while failing to set
   "__spec__.loader" is deprecated. In Python 3.16, "__loader__" will
   cease to be set or taken into consideration by the import system or
   the standard library.

module.__path__

   A (possibly empty) *sequence* of strings enumerating the locations
   where the package's submodules will be found. Non-package modules
   should not have a "__path__" attribute. See 모듈의 __path__ 어트리
   뷰트 for more details.

   It is **strongly** recommended that you use
   "module.__spec__.submodule_search_locations" instead of
   "module.__path__".

module.__file__

module.__cached__

   "__file__" and "__cached__" are both optional attributes that may
   or may not be set. Both attributes should be a "str" when they are
   available.

   "__file__" indicates the pathname of the file from which the module
   was loaded (if loaded from a file), or the pathname of the shared
   library file for extension modules loaded dynamically from a shared
   library. It might be missing for certain types of modules, such as
   C modules that are statically linked into the interpreter, and the
   import system may opt to leave it unset if it has no semantic
   meaning (for example, a module loaded from a database).

   If "__file__" is set then the "__cached__" attribute might also be
   set,  which is the path to any compiled version of the code (for
   example, a byte-compiled file). The file does not need to exist to
   set this attribute; the path can simply point to where the compiled
   file *would* exist (see **PEP 3147**).

   Note that "__cached__" may be set even if "__file__" is not set.
   However, that scenario is quite atypical.  Ultimately, the *loader*
   is what makes use of the module spec provided by the *finder* (from
   which "__file__" and "__cached__" are derived).  So if a loader can
   load from a cached module but otherwise does not load from a file,
   that atypical scenario may be appropriate.

   It is **strongly** recommended that you use
   "module.__spec__.cached" instead of "module.__cached__".

   Deprecated since version 3.13, will be removed in version 3.15:
   Setting "__cached__" on a module while failing to set
   "__spec__.cached" is deprecated. In Python 3.15, "__cached__" will
   cease to be set or taken into consideration by the import system or
   standard library.


3.2.9.2. Other writable attributes on module objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

As well as the import-related attributes listed above, module objects
also have the following writable attributes:

module.__doc__

   The module's documentation string, or "None" if unavailable. See
   also: "__doc__ attributes".

module.__annotations__

   A dictionary containing *variable annotations* collected during
   module body execution.  For best practices on working with
   "__annotations__", see "annotationlib".

   버전 3.14에서 변경: Annotations are now lazily evaluated. See **PEP
   649**.

module.__annotate__

   The *annotate function* for this module, or "None" if the module
   has no annotations. See also: "__annotate__" attributes.

   Added in version 3.14.


3.2.9.3. Module dictionaries
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Module objects also have the following special read-only attribute:

module.__dict__

   The module's namespace as a dictionary object. Uniquely among the
   attributes listed here, "__dict__" cannot be accessed as a global
   variable from within a module; it can only be accessed as an
   attribute on module objects.

   CPython 이 모듈 딕셔너리를 비우는 방법 때문에, 딕셔너리에 대한 참조
   가 남아있더라도, 모듈이 스코프를 벗어나면 모듈 딕셔너리는 비워집니
   다. 이것을 피하려면, 딕셔너리를 복사하거나 딕셔너리를 직접 이용하는
   동안은 모듈을 잡아두어야 합니다.


3.2.10. 사용자 정의 클래스(Custom classes)
------------------------------------------

Custom class types are typically created by class definitions (see
section 클래스 정의).  A class has a namespace implemented by a
dictionary object. Class attribute references are translated to
lookups in this dictionary, e.g., "C.x" is translated to
"C.__dict__["x"]" (although there are a number of hooks which allow
for other means of locating attributes). When the attribute name is
not found there, the attribute search continues in the base classes.
This search of the base classes uses the C3 method resolution order
which behaves correctly even in the presence of 'diamond' inheritance
structures where there are multiple inheritance paths leading back to
a common ancestor. Additional details on the C3 MRO used by Python can
be found at The Python 2.3 Method Resolution Order.

When a class attribute reference (for class "C", say) would yield a
class method object, it is transformed into an instance method object
whose "__self__" attribute is "C". When it would yield a
"staticmethod" object, it is transformed into the object wrapped by
the static method object. See section 디스크립터 구현하기 for another
way in which attributes retrieved from a class may differ from those
actually contained in its "__dict__".

클래스 어트리뷰트 대입은 클래스의 딕셔너리를 갱신할 뿐, 어떤 경우도 부
모 클래스의 딕셔너리를 건드리지는 않습니다.

클래스 객체는 클래스 인스턴스를 돌려주도록(아래를 보십시오) 호출될 수
있습니다(위를 보십시오).


3.2.10.1. Special attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+----------------------------------------------------+----------------------------------------------------+
| 어트리뷰트                                         | 의미                                               |
|====================================================|====================================================|
| type.__name__                                      | The class's name. See also: "__name__ attributes". |
+----------------------------------------------------+----------------------------------------------------+
| type.__qualname__                                  | The class's *qualified name*. See also:            |
|                                                    | "__qualname__ attributes".                         |
+----------------------------------------------------+----------------------------------------------------+
| type.__module__                                    | The name of the module in which the class was      |
|                                                    | defined.                                           |
+----------------------------------------------------+----------------------------------------------------+
| type.__dict__                                      | A "mapping proxy" providing a read-only view of    |
|                                                    | the class's namespace. See also: "__dict__         |
|                                                    | attributes".                                       |
+----------------------------------------------------+----------------------------------------------------+
| type.__bases__                                     | A "tuple" containing the class's bases. In most    |
|                                                    | cases, for a class defined as "class X(A, B, C)",  |
|                                                    | "X.__bases__" will be exactly equal to "(A, B,     |
|                                                    | C)".                                               |
+----------------------------------------------------+----------------------------------------------------+
| type.__base__                                      | **CPython 구현 상세:** The single base class in    |
|                                                    | the inheritance chain that is responsible for the  |
|                                                    | memory layout of instances. This attribute         |
|                                                    | corresponds to "tp_base" at the C level.           |
+----------------------------------------------------+----------------------------------------------------+
| type.__doc__                                       | The class's documentation string, or "None" if     |
|                                                    | undefined. Not inherited by subclasses.            |
+----------------------------------------------------+----------------------------------------------------+
| type.__annotations__                               | A dictionary containing *variable annotations*     |
|                                                    | collected during class body execution. See also:   |
|                                                    | "__annotations__ attributes".  For best practices  |
|                                                    | on working with "__annotations__", please see      |
|                                                    | "annotationlib". Use                               |
|                                                    | "annotationlib.get_annotations()" instead of       |
|                                                    | accessing this attribute directly.  경고:          |
|                                                    | Accessing the "__annotations__" attribute directly |
|                                                    | on a class object may return annotations for the   |
|                                                    | wrong class, specifically in certain cases where   |
|                                                    | the class, its base class, or a metaclass is       |
|                                                    | defined under "from __future__ import              |
|                                                    | annotations". See **749** for details.This         |
|                                                    | attribute does not exist on certain builtin        |
|                                                    | classes. On user-defined classes without           |
|                                                    | "__annotations__", it is an empty dictionary.  버  |
|                                                    | 전 3.14에서 변경: Annotations are now lazily       |
|                                                    | evaluated. See **PEP 649**.                        |
+----------------------------------------------------+----------------------------------------------------+
| type.__annotate__()                                | The *annotate function* for this class, or "None"  |
|                                                    | if the class has no annotations. See also:         |
|                                                    | "__annotate__ attributes".  Added in version 3.14. |
+----------------------------------------------------+----------------------------------------------------+
| type.__type_params__                               | A "tuple" containing the type parameters of a      |
|                                                    | generic class.  Added in version 3.12.             |
+----------------------------------------------------+----------------------------------------------------+
| type.__static_attributes__                         | A "tuple" containing names of attributes of this   |
|                                                    | class which are assigned through "self.X" from any |
|                                                    | function in its body.  Added in version 3.13.      |
+----------------------------------------------------+----------------------------------------------------+
| type.__firstlineno__                               | The line number of the first line of the class     |
|                                                    | definition, including decorators. Setting the      |
|                                                    | "__module__" attribute removes the                 |
|                                                    | "__firstlineno__" item from the type's dictionary. |
|                                                    | Added in version 3.13.                             |
+----------------------------------------------------+----------------------------------------------------+
| type.__mro__                                       | The "tuple" of classes that are considered when    |
|                                                    | looking for base classes during method resolution. |
+----------------------------------------------------+----------------------------------------------------+


3.2.10.2. Special methods
~~~~~~~~~~~~~~~~~~~~~~~~~

In addition to the special attributes described above, all Python
classes also have the following two methods available:

type.mro()

   This method can be overridden by a metaclass to customize the
   method resolution order for its instances.  It is called at class
   instantiation, and its result is stored in "__mro__".

type.__subclasses__()

   Each class keeps a list of weak references to its immediate
   subclasses. This method returns a list of all those references
   still alive. The list is in definition order. Example:

      >>> class A: pass
      >>> class B(A): pass
      >>> A.__subclasses__()
      [<class 'B'>]


3.2.11. 클래스 인스턴스(Class instances)
----------------------------------------

A class instance is created by calling a class object (see above).  A
class instance has a namespace implemented as a dictionary which is
the first place in which attribute references are searched.  When an
attribute is not found there, and the instance's class has an
attribute by that name, the search continues with the class
attributes.  If a class attribute is found that is a user-defined
function object, it is transformed into an instance method object
whose "__self__" attribute is the instance.  Static method and class
method objects are also transformed; see above under "Classes".  See
section 디스크립터 구현하기 for another way in which attributes of a
class retrieved via its instances may differ from the objects actually
stored in the class's "__dict__".  If no class attribute is found, and
the object's class has a "__getattr__()" method, that is called to
satisfy the lookup.

Attribute assignments and deletions update the instance's dictionary,
never a class's dictionary.  If the class has a "__setattr__()" or
"__delattr__()" method, this is called instead of updating the
instance dictionary directly.

어떤 특별한 이름들의 메서드들을 가지면, 클래스 인스턴스는 숫자, 시퀀스
, 매핑인 척할 수 있습니다. 특수 메서드 이름들 섹션을 보십시오.


3.2.11.1. Special attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

object.__class__

   The class to which a class instance belongs.

object.__dict__

   A dictionary or other mapping object used to store an object's
   (writable) attributes. Not all instances have a "__dict__"
   attribute; see the section on __slots__ for more details.


3.2.12. I/O 객체 (파일 객체라고도 알려져 있습니다)
--------------------------------------------------

*파일 객체* 는 열린 파일을 나타냅니다. 파일 객체를 만드는 여러 가지 단
축법이 있습니다: "open()" 내장 함수, "os.popen()", "os.fdopen()" 과 소
켓 객체의 "makefile()" 메서드 (그리고, 아마도 확장 모듈들이 제공하는
다른 함수들이나 메서드들).

"sys.stdin", "sys.stdout", "sys.stderr" 는 인터프리터의 표준 입력, 출
력, 에러 스트림으로 초기화된 파일 객체들입니다; 모두 텍스트 모드로 열
려서 "io.TextIOBase" 추상 클래스에 의해 정의된 인터페이스를 따릅니다.


3.2.13. 내부 형(Internal types)
-------------------------------

인터프리터가 내부적으로 사용하는 몇몇 형들은 사용자에게 노출됩니다. 인
터프리터의 미래 버전에서 이들의 정의는 변경될 수 있지만, 완전함을 위해
여기서 언급합니다.


3.2.13.1. 코드 객체(Code objects)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

코드 객체는 *바이트로 컴파일된(byte-compiled)* 실행 가능한 파이썬 코드
를 나타내는데, 그냥 *바이트 코드* 라고도 부릅니다. 코드 객체와 함수 객
체 간에는 차이가 있습니다; 함수 객체는 함수의 전역 공간(globals) (함수
가 정의된 모듈)을 명시적으로 참조하고 있지만, 코드 객체는 어떤 문맥
(context)도 갖고 있지 않습니다; 또한 기본 인자값들이 함수 객체에 저장
되어 있지만 코드 객체에는 들어있지 않습니다 (실행 시간에 계산되는 값들
을 나타내기 때문입니다). 함수 객체와는 달리, 코드 객체는 불변이고 가변
객체들에 대한 어떤 참조도 (직접 혹은 간접적으로도) 갖고 있지 않습니다.


3.2.13.1.1. Special read-only attributes
""""""""""""""""""""""""""""""""""""""""

+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_name                                 | The function name                                  |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_qualname                             | The fully qualified function name  Added in        |
|                                                    | version 3.11.                                      |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_argcount                             | The total number of positional *parameters*        |
|                                                    | (including positional-only parameters and          |
|                                                    | parameters with default values) that the function  |
|                                                    | has                                                |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_posonlyargcount                      | The number of positional-only *parameters*         |
|                                                    | (including arguments with default values) that the |
|                                                    | function has                                       |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_kwonlyargcount                       | The number of keyword-only *parameters* (including |
|                                                    | arguments with default values) that the function   |
|                                                    | has                                                |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_nlocals                              | The number of local variables used by the function |
|                                                    | (including parameters)                             |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_varnames                             | A "tuple" containing the names of the local        |
|                                                    | variables in the function (starting with the       |
|                                                    | parameter names)                                   |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_cellvars                             | A "tuple" containing the names of local variables  |
|                                                    | that are referenced from at least one *nested      |
|                                                    | scope* inside the function                         |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_freevars                             | A "tuple" containing the names of *free (closure)  |
|                                                    | variables* that a *nested scope* references in an  |
|                                                    | outer scope. See also "function.__closure__".      |
|                                                    | Note: references to global and builtin names are   |
|                                                    | *not* included.                                    |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_code                                 | A string representing the sequence of *bytecode*   |
|                                                    | instructions in the function                       |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_consts                               | A "tuple" containing the literals used by the      |
|                                                    | *bytecode* in the function                         |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_names                                | A "tuple" containing the names used by the         |
|                                                    | *bytecode* in the function                         |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_filename                             | The name of the file from which the code was       |
|                                                    | compiled                                           |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_firstlineno                          | The line number of the first line of the function  |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_lnotab                               | A string encoding the mapping from *bytecode*      |
|                                                    | offsets to line numbers. For details, see the      |
|                                                    | source code of the interpreter.  버전 3.12부터 폐  |
|                                                    | 지됨: This attribute of code objects is            |
|                                                    | deprecated, and may be removed in Python 3.15.     |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_stacksize                            | The required stack size of the code object         |
+----------------------------------------------------+----------------------------------------------------+
| codeobject.co_flags                                | An "integer" encoding a number of flags for the    |
|                                                    | interpreter.                                       |
+----------------------------------------------------+----------------------------------------------------+

The following flag bits are defined for "co_flags": bit "0x04" is set
if the function uses the "*arguments" syntax to accept an arbitrary
number of positional arguments; bit "0x08" is set if the function uses
the "**keywords" syntax to accept arbitrary keyword arguments; bit
"0x20" is set if the function is a generator. See 코드 객체 비트 플래
그 for details on the semantics of each flags that might be present.

Future feature declarations (for example, "from __future__ import
division") also use bits in "co_flags" to indicate whether a code
object was compiled with a particular feature enabled. See
"compiler_flag".

Other bits in "co_flags" are reserved for internal use.

If a code object represents a function and has a docstring, the
"CO_HAS_DOCSTRING" bit is set in "co_flags" and the first item in
"co_consts" is the docstring of the function.


3.2.13.1.2. Methods on code objects
"""""""""""""""""""""""""""""""""""

codeobject.co_positions()

   Returns an iterable over the source code positions of each
   *bytecode* instruction in the code object.

   The iterator returns "tuple"s containing the "(start_line,
   end_line, start_column, end_column)". The *i-th* tuple corresponds
   to the position of the source code that compiled to the *i-th* code
   unit. Column information is 0-indexed utf-8 byte offsets on the
   given source line.

   This positional information can be missing. A non-exhaustive lists
   of cases where this may happen:

   * Running the interpreter with "-X" "no_debug_ranges".

   * Loading a pyc file compiled while using "-X" "no_debug_ranges".

   * Position tuples corresponding to artificial instructions.

   * Line and column numbers that can't be represented due to
     implementation specific limitations.

   When this occurs, some or all of the tuple elements can be "None".

   Added in version 3.11.

   참고:

     This feature requires storing column positions in code objects
     which may result in a small increase of disk usage of compiled
     Python files or interpreter memory usage. To avoid storing the
     extra information and/or deactivate printing the extra traceback
     information, the "-X" "no_debug_ranges" command line flag or the
     "PYTHONNODEBUGRANGES" environment variable can be used.

codeobject.co_lines()

   Returns an iterator that yields information about successive ranges
   of *bytecode*s. Each item yielded is a "(start, end, lineno)"
   "tuple":

   * "start" (an "int") represents the offset (inclusive) of the start
     of the *bytecode* range

   * "end" (an "int") represents the offset (exclusive) of the end of
     the *bytecode* range

   * "lineno" is an "int" representing the line number of the
     *bytecode* range, or "None" if the bytecodes in the given range
     have no line number

   The items yielded will have the following properties:

   * The first range yielded will have a "start" of 0.

   * The "(start, end)" ranges will be non-decreasing and consecutive.
     That is, for any pair of "tuple"s, the "start" of the second will
     be equal to the "end" of the first.

   * No range will be backwards: "end >= start" for all triples.

   * The last "tuple" yielded will have "end" equal to the size of the
     *bytecode*.

   Zero-width ranges, where "start == end", are allowed. Zero-width
   ranges are used for lines that are present in the source code, but
   have been eliminated by the *bytecode* compiler.

   Added in version 3.10.

   더 보기:

     **PEP 626** - Precise line numbers for debugging and other tools.
        The PEP that introduced the "co_lines()" method.

codeobject.replace(**kwargs)

   Return a copy of the code object with new values for the specified
   fields.

   Code objects are also supported by the generic function
   "copy.replace()".

   Added in version 3.8.


3.2.13.2. 프레임 객체(Frame objects)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Frame objects represent execution frames.  They may occur in traceback
objects, and are also passed to registered trace functions.


3.2.13.2.1. Special read-only attributes
""""""""""""""""""""""""""""""""""""""""

+----------------------------------------------------+----------------------------------------------------+
| frame.f_back                                       | Points to the previous stack frame (towards the    |
|                                                    | caller), or "None" if this is the bottom stack     |
|                                                    | frame                                              |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_code                                       | The code object being executed in this frame.      |
|                                                    | Accessing this attribute raises an auditing event  |
|                                                    | "object.__getattr__" with arguments "obj" and      |
|                                                    | ""f_code"".                                        |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_locals                                     | The mapping used by the frame to look up local     |
|                                                    | variables. If the frame refers to an *optimized    |
|                                                    | scope*, this may return a write-through proxy      |
|                                                    | object.  버전 3.13에서 변경: Return a proxy for    |
|                                                    | optimized scopes.                                  |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_globals                                    | The dictionary used by the frame to look up global |
|                                                    | variables                                          |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_builtins                                   | The dictionary used by the frame to look up built- |
|                                                    | in (intrinsic) names                               |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_lasti                                      | The "precise instruction" of the frame object      |
|                                                    | (this is an index into the *bytecode* string of    |
|                                                    | the code object)                                   |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_generator                                  | The *generator* or *coroutine* object that owns    |
|                                                    | this frame, or "None" if the frame is a normal     |
|                                                    | function.  Added in version 3.14.                  |
+----------------------------------------------------+----------------------------------------------------+


3.2.13.2.2. Special writable attributes
"""""""""""""""""""""""""""""""""""""""

+----------------------------------------------------+----------------------------------------------------+
| frame.f_trace                                      | If not "None", this is a function called for       |
|                                                    | various events during code execution (this is used |
|                                                    | by debuggers). Normally an event is triggered for  |
|                                                    | each new source line (see "f_trace_lines").        |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_trace_lines                                | Set this attribute to "False" to disable           |
|                                                    | triggering a tracing event for each source line.   |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_trace_opcodes                              | Set this attribute to "True" to allow per-opcode   |
|                                                    | events to be requested. Note that this may lead to |
|                                                    | undefined interpreter behaviour if exceptions      |
|                                                    | raised by the trace function escape to the         |
|                                                    | function being traced.                             |
+----------------------------------------------------+----------------------------------------------------+
| frame.f_lineno                                     | The current line number of the frame -- writing to |
|                                                    | this from within a trace function jumps to the     |
|                                                    | given line (only for the bottom-most frame).  A    |
|                                                    | debugger can implement a Jump command (aka Set     |
|                                                    | Next Statement) by writing to this attribute.      |
+----------------------------------------------------+----------------------------------------------------+


3.2.13.2.3. Frame object methods
""""""""""""""""""""""""""""""""

프레임 객체는 한가지 메서드를 지원합니다:

frame.clear()

   This method clears all references to local variables held by the
   frame.  Also, if the frame belonged to a *generator*, the generator
   is finalized.  This helps break reference cycles involving frame
   objects (for example when catching an exception and storing its
   traceback for later use).

   "RuntimeError" is raised if the frame is currently executing or
   suspended.

   Added in version 3.4.

   버전 3.13에서 변경: Attempting to clear a suspended frame raises
   "RuntimeError" (as has always been the case for executing frames).


3.2.13.3. 트레이스백 객체(Traceback objects)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Traceback objects represent the stack trace of an exception. A
traceback object is implicitly created when an exception occurs, and
may also be explicitly created by calling "types.TracebackType".

버전 3.7에서 변경: Traceback objects can now be explicitly
instantiated from Python code.

For implicitly created tracebacks, when the search for an exception
handler unwinds the execution stack, at each unwound level a traceback
object is inserted in front of the current traceback.  When an
exception handler is entered, the stack trace is made available to the
program. (See section try 문.) It is accessible as the third item of
the tuple returned by "sys.exc_info()", and as the "__traceback__"
attribute of the caught exception.

When the program contains no suitable handler, the stack trace is
written (nicely formatted) to the standard error stream; if the
interpreter is interactive, it is also made available to the user as
"sys.last_traceback".

For explicitly created tracebacks, it is up to the creator of the
traceback to determine how the "tb_next" attributes should be linked
to form a full stack trace.

Special read-only attributes:

+----------------------------------------------------+----------------------------------------------------+
| traceback.tb_frame                                 | Points to the execution frame of the current       |
|                                                    | level.  Accessing this attribute raises an         |
|                                                    | auditing event "object.__getattr__" with arguments |
|                                                    | "obj" and ""tb_frame"".                            |
+----------------------------------------------------+----------------------------------------------------+
| traceback.tb_lineno                                | Gives the line number where the exception occurred |
+----------------------------------------------------+----------------------------------------------------+
| traceback.tb_lasti                                 | Indicates the "precise instruction".               |
+----------------------------------------------------+----------------------------------------------------+

The line number and last instruction in the traceback may differ from
the line number of its frame object if the exception occurred in a
"try" statement with no matching except clause or with a "finally"
clause.

traceback.tb_next

   The special writable attribute "tb_next" is the next level in the
   stack trace (towards the frame where the exception occurred), or
   "None" if there is no next level.

   버전 3.7에서 변경: This attribute is now writable


3.2.13.4. 슬라이스 객체(Slice objects)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Slice objects are used to represent slices for "__getitem__()"
methods.  They are also created by the built-in "slice()" function.

특수 읽기 전용 어트리뷰트들: "start" 는 하한(lower bound) 입니다;
"stop" 은 상한(upper bound) 입니다; "step" 은 스텝 값입니다; 각 값은
생략될 경우 "None" 입니다. 이 어트리뷰트들은 임의의 형이 될 수 있습니
다.

슬라이스 객체는 하나의 메서드를 지원합니다.

slice.indices(self, length)

   이 메서드는 하나의 정수 인자 *length* 를 받아서 슬라이스 객체가 길
   이 *length* 인 시퀀스에 적용되었을 때 그 슬라이스에 대한 정보를 계
   산합니다. 세 개의 정수로 구성된 튜플을 돌려줍니다: 이것들은 각각
   *start* 와 *stop* 인덱스와, *step* 또는 슬라이스의 스트라이드
   (stride) 길이입니다. 생략되었거나 범위를 벗어난 인덱스들은 일반적인
   슬라이스와 같은 방법으로 다뤄집니다.


3.2.13.5. 스태틱 메서드 객체(Static method objects)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Static method objects provide a way of defeating the transformation of
function objects to method objects described above. A static method
object is a wrapper around any other object, usually a user-defined
method object. When a static method object is retrieved from a class
or a class instance, the object actually returned is the wrapped
object, which is not subject to any further transformation. Static
method objects are also callable. Static method objects are created by
the built-in "staticmethod()" constructor.


3.2.13.6. 클래스 메서드 객체(Class method objects)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

A class method object, like a static method object, is a wrapper
around another object that alters the way in which that object is
retrieved from classes and class instances. The behaviour of class
method objects upon such retrieval is described above, under "instance
methods". Class method objects are created by the built-in
"classmethod()" constructor.


3.3. 특수 메서드 이름들
=======================

A class can implement certain operations that are invoked by special
syntax (such as arithmetic operations or subscripting and slicing) by
defining methods with special names. This is Python's approach to
*operator overloading*, allowing classes to define their own behavior
with respect to language operators.  For instance, if a class defines
a method named "__getitem__()", and "x" is an instance of this class,
then "x[i]" is roughly equivalent to "type(x).__getitem__(x, i)".
Except where mentioned, attempts to execute an operation raise an
exception when no appropriate method is defined (typically
"AttributeError" or "TypeError").

Setting a special method to "None" indicates that the corresponding
operation is not available.  For example, if a class sets "__iter__()"
to "None", the class is not iterable, so calling "iter()" on its
instances will raise a "TypeError" (without falling back to
"__getitem__()"). [2]

When implementing a class that emulates any built-in type, it is
important that the emulation only be implemented to the degree that it
makes sense for the object being modelled.  For example, some
sequences may work well with retrieval of individual elements, but
extracting a slice may not make sense. (One example of this is the
NodeList interface in the W3C's Document Object Model.)


3.3.1. 기본적인 커스터마이제이션
--------------------------------

object.__new__(cls[, ...])

   클래스 *cls* 의 새 인스턴스를 만들기 위해 호출됩니다. "__new__()"
   는 스태틱 메서드입니다 (그렇게 선언하지 않아도 되는 특별한 경우입니
   다)인데, 첫 번째 인자로 만들려고 하는 인스턴스의 클래스가 전달됩니
   다. 나머지 인자들은 객체 생성자 표현(클래스 호출)에 전달된 것들입니
   다. "__new__()" 의 반환 값은 새 객체 인스턴스이어야 합니다 (보통
   *cls* 의 인스턴스).

   Typical implementations create a new instance of the class by
   invoking the superclass's "__new__()" method using
   "super().__new__(cls[, ...])" with appropriate arguments and then
   modifying the newly created instance as necessary before returning
   it.

   If "__new__()" is invoked during object construction and it returns
   an instance of *cls*, then the new instance’s "__init__()" method
   will be invoked like "__init__(self[, ...])", where *self* is the
   new instance and the remaining arguments are the same as were
   passed to the object constructor.

   만약 "__new__()" 가 *cls* 의 인스턴스를 돌려주지 않으면, 새 인스턴
   스의 "__init__()" 는 호출되지 않습니다.

   "__new__()" 는 주로 불변형(int, str, tuple과 같은)의 서브 클래스가
   인스턴스 생성을 커스터마이즈할 수 있도록 하는 데 사용됩니다. 또한,
   사용자 정의 메타 클래스에서 클래스 생성을 커스터마이즈하기 위해 자
   주 사용됩니다.

object.__init__(self[, ...])

   ("__new__()" 에 의해) 인스턴스가 만들어진 후에, 하지만 호출자에게
   돌려주기 전에 호출됩니다. 인자들은 클래스 생성자 표현으로 전달된 것
   들입니다. 만약 베이스 클래스가 "__init__()" 메서드를 갖고 있다면,
   서브 클래스의 "__init__()" 메서드는, 있다면, 인스턴스에서 베이스 클
   래스가 차지하는 부분이 올바르게 초기화됨을 확실히 하기 위해 명시적
   으로 호출해주어야 합니다; 예를 들어: "super().__init__([args...])".

   객체를 만드는데 "__new__()" 와 "__init__()" 가 협력하고 있으므로
   ("__new__()" 는 만들고, "__init__()" 는 그것을 커스터마이즈합니다),
   "__init__()" 가 "None" 이외의 값을 돌려주면 실행시간에 "TypeError"
   를 일으킵니다.

object.__del__(self)

   인스턴스가 파괴되기 직전에 호출됩니다. 파이널라이저 또는 (부적절하
   게) 파괴자라고 불립니다. 만약 베이스 클래스가 "__del__()" 메서드를
   갖고 있다면, 자식 클래스의 "__del__()" 메서드는, 정의되어 있다면,
   인스턴스에서 베이스 클래스가 차지하는 부분을 적절하게 삭제하기 위해
   , 명시적으로 베이스 클래스의 메서드를 호출해야 합니다.

   (권장하지는 않지만!) "__del__()" 메서드는 인스턴스에 대한 새로운 참
   조를 만듦으로써 인스턴스의 파괴를 지연시킬 수 있습니다. 이것을 객체
   *부활* 이라고 부릅니다. 부활한 객체가 파괴될 때 "__del__()" 이 두
   번째로 호출될지는 구현에 따라 다릅니다; 현재 *CPython* 구현은 오직
   한 번만 호출합니다.

   It is not guaranteed that "__del__()" methods are called for
   objects that still exist when the interpreter exits.
   "weakref.finalize" provides a straightforward way to register a
   cleanup function to be called when an object is garbage collected.

   참고:

     "del x" 는 직접 "x.__del__()" 를 호출하지 않습니다 --- 앞에 있는
     것은 "x" 의 참조 횟수(reference count)를 하나 감소시키고, 뒤에 있
     는 것은 "x" 의 참조 횟수가 0 이 될 때 호출됩니다.

   **CPython 구현 상세:** It is possible for a reference cycle to
   prevent the reference count of an object from going to zero.  In
   this case, the cycle will be later detected and deleted by the
   *cyclic garbage collector*.  A common cause of reference cycles is
   when an exception has been caught in a local variable.  The frame's
   locals then reference the exception, which references its own
   traceback, which references the locals of all frames caught in the
   traceback.

   더 보기: "gc" 모듈에 대한 문서.

   경고:

     "__del__()" 이 호출되는 불안정한 상황 때문에, 이것이 실행 중에 발
     생시키는 예외는 무시되고, 대신에 "sys.stderr" 로 경고가 출력됩니
     다. 특히:

     * "__del__()" 은 (임의의 스레드에서) 임의의 코드가 실행되는 동안
       호출될 수 있습니다. "__del__()" 이 록을 얻어야 하거나 다른 블로
       킹 자원을 호출하면, "__del__()" 을 실행하기 위해 중단된 코드가
       자원을 이미 차지했을 수 있으므로 교착 상태에 빠질 수 있습니다.

     * "__del__()" 은 인터프리터를 종료할 때 실행될 수 있습니다. 결과
       적으로, 액세스해야 하는 전역 변수(다른 모듈 포함)가 이미 삭제되
       었거나 "None" 으로 설정되었을 수 있습니다. 파이썬은 이름이 하나
       의 밑줄로 시작하는 전역 객체가 다른 전역 객체들보다 먼저 삭제됨
       을 보장합니다; 이것은, 만약 그 전역 객체들에 대한 다른 참조가
       존재하지 않는다면, "__del__()" 메서드가 호출되는 시점에, 임포트
       된 모듈들이 남아있도록 확실히 하는 데 도움이 될 수 있습니다.

object.__repr__(self)

   "repr()" 내장 함수에 의해 호출되어 객체의 "형식적인(official)" 문자
   열 표현을 계산합니다. 만약 가능하다면, 이것은 같은 (적절한 환경이
   주어질 때) 값을 갖는 객체를 새로 만들 수 있는 올바른 파이썬 표현식
   처럼 보여야 합니다. 가능하지 않다면, "<...쓸모있는 설명...>" 형태의
   문자열을 돌려줘야 합니다. 반환 값은 반드시 문자열이어야 합니다. 만
   약 클래스가 "__str__()" 없이 "__repr__()" 만 정의한다면,
   "__repr__()" 은 그 클래스 인스턴스의 "비형식적인(informal)" 문자열
   표현이 요구될 때 사용될 수 있습니다.

   This is typically used for debugging, so it is important that the
   representation is information-rich and unambiguous. A default
   implementation is provided by the "object" class itself.

object.__str__(self)

   Called by "str(object)", the default "__format__()" implementation,
   and the built-in function "print()", to compute the "informal" or
   nicely printable string representation of an object.  The return
   value must be a str object.

   이 메서드는 "__str__()" 이 올바른 파이썬 표현식을 돌려줄 것이라고
   기대되지 않는다는 점에서 "object.__repr__()" 과 다릅니다: 더 편리하
   고 간결한 표현이 사용될 수 있습니다.

   내장형 "object" 에 정의된 기본 구현은 "object.__repr__()" 을 호출합
   니다.

object.__bytes__(self)

   Called by bytes to compute a byte-string representation of an
   object. This should return a "bytes" object. The "object" class
   itself does not provide this method.

object.__format__(self, format_spec)

   "format()" 내장 함수, 확대하면, 포맷 문자열 리터럴(formatted string
   literals) 의 계산과 "str.format()" 메서드에 의해 호출되어, 객체의 "
   포맷된" 문자열 표현을 만들어냅니다. *format_spec* 인자는 요구되는
   포맷 옵션들을 포함하는 문자열입니다. *format_spec* 인자의 해석은
   "__format__()" 을 구현하는 형에 달려있으나, 대부분 클래스는 포매팅
   을 내향형들의 하나로 위임하거나, 비슷한 포맷 옵션 문법을 사용합니다
   .

   표준 포매팅 문법에 대해서는 포맷 명세 미니 언어 를 참고하면 됩니다.

   반환 값은 반드시 문자열이어야 합니다.

   The default implementation by the "object" class should be given an
   empty *format_spec* string. It delegates to "__str__()".

   버전 3.4에서 변경: "object" 의 __format__ 메서드 자신은, 빈 문자열
   이 아닌 인자가 전달되면 "TypeError" 를 발생시킵니다.

   버전 3.7에서 변경: 이제 "object.__format__(x, '')" 는
   "format(str(x), '')" 가 아니라 "str(x)" 와 동등합니다.

object.__lt__(self, other)
object.__le__(self, other)
object.__eq__(self, other)
object.__ne__(self, other)
object.__gt__(self, other)
object.__ge__(self, other)

   이것들은 소위 "풍부한 비교(rich comparison)" 메서드입니다. 연산자
   기호와 메서드 이름 간의 관계는 다음과 같습니다: "x<y" 는
   "x.__lt__(y)" 를 호출합니다, "x<=y" 는 "x.__le__(y)" 를 호출합니다,
   "x==y" 는 "x.__eq__(y)" 를 호출합니다, "x!=y" 는 "x.__ne__(y)" 를
   호출합니다, "x>y" 는 "x.__gt__(y)" 를 호출합니다, "x>=y" 는
   "x.__ge__(y)" 를 호출합니다.

   A rich comparison method may return the singleton "NotImplemented"
   if it does not implement the operation for a given pair of
   arguments. By convention, "False" and "True" are returned for a
   successful comparison. However, these methods can return any value,
   so if the comparison operator is used in a Boolean context (e.g.,
   in the condition of an "if" statement), Python will call "bool()"
   on the value to determine if the result is true or false.

   By default, "object" implements "__eq__()" by using "is", returning
   "NotImplemented" in the case of a false comparison: "True if x is y
   else NotImplemented". For "__ne__()", by default it delegates to
   "__eq__()" and inverts the result unless it is "NotImplemented".
   There are no other implied relationships among the comparison
   operators or default implementations; for example, the truth of
   "(x<y or x==y)" does not imply "x<=y". To automatically generate
   ordering operations from a single root operation, see
   "functools.total_ordering()".

   By default, the "object" class provides implementations consistent
   with 값 비교: equality compares according to object identity, and
   order comparisons raise "TypeError". Each default method may
   generate these results directly, but may also return
   "NotImplemented".

   사용자 정의 비교 연산자를 지원하고 딕셔너리 키로 사용될 수 있는 *해
   시 가능* 객체를 만드는 것에 관한 몇 가지 중요한 내용이 "__hash__()"
   에 관한 문단에 나옵니다.

   There are no swapped-argument versions of these methods (to be used
   when the left argument does not support the operation but the right
   argument does); rather, "__lt__()" and "__gt__()" are each other's
   reflection, "__le__()" and "__ge__()" are each other's reflection,
   and "__eq__()" and "__ne__()" are their own reflection. If the
   operands are of different types, and the right operand's type is a
   direct or indirect subclass of the left operand's type, the
   reflected method of the right operand has priority, otherwise the
   left operand's method has priority.  Virtual subclassing is not
   considered.

   When no appropriate method returns any value other than
   "NotImplemented", the "==" and "!=" operators will fall back to
   "is" and "is not", respectively.

object.__hash__(self)

   Called by built-in function "hash()" and for operations on members
   of hashed collections including "set", "frozenset", and "dict".
   The "__hash__()" method should return an integer. The only required
   property is that objects which compare equal have the same hash
   value; it is advised to mix together the hash values of the
   components of the object that also play a part in comparison of
   objects by packing them into a tuple and hashing the tuple.
   Example:

      def __hash__(self):
          return hash((self.name, self.nick, self.color))

   참고:

     "hash()" 는 객체가 정의한 "__hash__()" 메서드가 돌려주는 값을
     "Py_ssize_t" 의 크기로 자릅니다(truncate). 이것은 보통 64-bit 빌
     드에서는 8바이트고, 32-bit 빌드에서는 4바이트입니다. 만약 객체의
     "__hash__()" 가 서로 다른 비트 크기를 갖는 빌드들 사이에서 함께
     사용되어야 한다면, 모든 지원할 빌드들에서의 폭을 검사해야 합니다.
     이렇게 하는 쉬운 방법은 "python -c "import sys;
     print(sys.hash_info.width)"" 입니다.

   If a class does not define an "__eq__()" method it should not
   define a "__hash__()" operation either; if it defines "__eq__()"
   but not "__hash__()", its instances will not be usable as items in
   hashable collections.  If a class defines mutable objects and
   implements an "__eq__()" method, it should not implement
   "__hash__()", since the implementation of *hashable* collections
   requires that a key's hash value is immutable (if the object's hash
   value changes, it will be in the wrong hash bucket).

   User-defined classes have "__eq__()" and "__hash__()" methods by
   default (inherited from the "object" class); with them, all objects
   compare unequal (except with themselves) and "x.__hash__()" returns
   an appropriate value such that "x == y" implies both that "x is y"
   and "hash(x) == hash(y)".

   "__eq__()" 를 재정의하고 "__hash__()" 를 정의하지 않는 클래스는
   "__hash__()" 가 "None" 으로 설정됩니다. 클래스의 "__hash__()" 메서
   드가 "None" 이면, 클래스의 인스턴스는 프로그램이 해시값을 얻으려 시
   도할 때 "TypeError" 를 일으키고, "isinstance(obj,
   collections.abc.Hashable)" 로 검사할 때 해시 가능하지 않다고 올바로
   감지됩니다.

   만약 "__eq__()" 를 재정의하는 클래스가 부모 클래스로부터
   "__hash__()" 의 구현을 물려받고 싶으면 인터프리터에게 명시적으로 이
   렇게 지정해주어야 합니다: "__hash__ = <ParentClass>.__hash__".

   만약 "__eq__()" 를 재정의하지 않는 클래스가 해시 지원을 멈추고 싶으
   면, 클래스 정의에 "__hash__ = None" 을 포함해야 합니다. 자신의
   "__hash__()" 을 정의한 후에 직접 "TypeError" 를 일으키는 경우는
   "isinstance(obj, collections.abc.Hashable)" 호출이 해시 가능하다고
   잘못 인식합니다.

   참고:

     기본적으로, str과 bytes 객체들의 "__hash__()" 값은 예측할 수 없는
     난수값으로 "솔트되어(salted)" 있습니다. 개별 파이썬 프로세스 내에
     서는 변하지 않는 값으로 유지되지만, 파이썬을 반복적으로 실행할 때
     는 예측할 수 없게 됩니다.This is intended to provide protection
     against a denial-of-service caused by carefully chosen inputs
     that exploit the worst case performance of a dict insertion,
     *O*(*n*^2) complexity.  See
     http://ocert.org/advisories/ocert-2011-003.html for details.해시
     값의 변경은 집합의 이터레이션 순서에 영향을 줍니다, 파이썬은 이
     순서에 대해 어떤 보장도 하지 않습니다 (그리고 보통 32-bit 와
     64-bit 빌드 사이에서도 다릅니다)."PYTHONHASHSEED" 를 참고하십시오
     .

   버전 3.3에서 변경: 해시 난수 화는 기본적으로 활성화됩니다.

object.__bool__(self)

   Called to implement truth value testing and the built-in operation
   "bool()"; should return "False" or "True".  When this method is not
   defined, "__len__()" is called, if it is defined, and the object is
   considered true if its result is nonzero.  If a class defines
   neither "__len__()" nor "__bool__()" (which is true of the "object"
   class itself), all its instances are considered true.


3.3.2. 어트리뷰트 액세스 커스터마이제이션
-----------------------------------------

클래스 인스턴스의 어트리뷰트 참조(읽기, 대입하기, "x.name" 을 삭제하기
)의 의미를 변경하기 위해 다음과 같은 메서드들이 정의될 수 있습니다.

object.__getattr__(self, name)

   Called when the default attribute access fails with an
   "AttributeError" (either "__getattribute__()" raises an
   "AttributeError" because *name* is not an instance attribute or an
   attribute in the class tree for "self"; or "__get__()" of a *name*
   property raises "AttributeError").  This method should either
   return the (computed) attribute value or raise an "AttributeError"
   exception. The "object" class itself does not provide this method.

   Note that if the attribute is found through the normal mechanism,
   "__getattr__()" is not called.  (This is an intentional asymmetry
   between "__getattr__()" and "__setattr__()".) This is done both for
   efficiency reasons and because otherwise "__getattr__()" would have
   no way to access other attributes of the instance.  Note that at
   least for instance variables, you can take total control by not
   inserting any values in the instance attribute dictionary (but
   instead inserting them in another object).  See the
   "__getattribute__()" method below for a way to actually get total
   control over attribute access.

object.__getattribute__(self, name)

   클래스 인스턴스의 어트리뷰트 액세스를 구현하기 위해 조건 없이 호출
   됩니다. 만약 클래스가 "__getattr__()" 도 함께 구현하면,
   "__getattribute__()" 가 명시적으로 호출하거나 "AttributeError" 를
   일으키지 않는 이상 *__getattr__* 는 호출되지 않습니다. 이 메서드는
   어트리뷰트의 (계산된) 값을 돌려주거나 "AttributeError" 예외를 일으
   켜야 합니다. 이 메서드에서 무한 재귀(infinite recursion)가 발생하는
   것을 막기 위해, 구현은 언제나 필요한 어트리뷰트에 접근하기 위해 같
   은 이름의 베이스 클래스의 메서드를 호출해야 합니다. 예를 들어,
   "object.__getattribute__(self, name)".

   참고:

     This method may still be bypassed when looking up special methods
     as the result of implicit invocation via language syntax or
     built-in functions. See 특수 메서드 조회.

   특정 민감한 어트리뷰트 액세스의 경우, 인자 "obj"와 "name"으로 감사
   이벤트 "object.__getattr__"을 발생시킵니다.

object.__setattr__(self, name, value)

   어트리뷰트 대입이 시도될 때 호출됩니다. 일반적인 메커니즘(즉 인스턴
   스 딕셔너리에 값을 저장하는 것) 대신에 이것이 호출됩니다. *name* 은
   어트리뷰트 이름이고, *value* 는 그것에 대입하려는 값입니다.

   "__setattr__()" 에서 인스턴스 어트리뷰트에 대입하려고 할 때는, 같은
   이름의 베이스 클래스의 메서드를 호출해야 합니다. 예를 들어
   "object.__setattr__(self, name, value)"

   특정 민감한 어트리뷰트 대입의 경우, 인자 "obj", "name", "value"로
   감사 이벤트 "object.__setattr__"을 발생시킵니다.

object.__delattr__(self, name)

   "__setattr__()" 과 비슷하지만 어트리뷰트를 대입하는 대신에 삭제합니
   다. 이것은 "del obj.name" 이 객체에 의미가 있는 경우에만 구현되어야
   합니다.

   특정 민감한 어트리뷰트 삭제의 경우, 인자 "obj"와 "name"으로 감사 이
   벤트 "object.__delattr__"을 발생시킵니다.

object.__dir__(self)

   Called when "dir()" is called on the object. An iterable must be
   returned. "dir()" converts the returned iterable to a list and
   sorts it.


3.3.2.1. 모듈 어트리뷰트 액세스 커스터마이제이션
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

module.__getattr__()
module.__dir__()

특수한 이름 "__getattr__" 과 "__dir__" 는 모듈 어트리뷰트에 대한 접근
을 사용자 정의하는 데 사용될 수도 있습니다. 모듈 수준의 "__getattr__"
함수는 하나의 인자로 어트리뷰트의 이름을 받아서 계산된 값을 돌려주거나
"AttributeError" 를 발생시켜야 합니다. 일반적인 조회(즉
"object.__getattribute__()")를 통해 어트리뷰트가 모듈 객체에서 발견되
지 않으면, "AttributeError" 를 일으키기 전에 모듈 "__dict__" 에서
"__getattr__" 을 검색합니다. 발견되면, 어트리뷰트 이름으로 그 함수를
호출하고 결과를 돌려줍니다.

The "__dir__" function should accept no arguments, and return an
iterable of strings that represents the names accessible on module. If
present, this function overrides the standard "dir()" search on a
module.

module.__class__

모듈 동작(어트리뷰트 설정, 프로퍼티 등)을 보다 세밀하게 사용자 정의하
려면, 모듈 객체의 "__class__" 어트리뷰트를 "types.ModuleType" 의 서브
클래스로 설정할 수 있습니다. 예를 들면:

   import sys
   from types import ModuleType

   class VerboseModule(ModuleType):
       def __repr__(self):
           return f'Verbose {self.__name__}'

       def __setattr__(self, attr, value):
           print(f'Setting {attr}...')
           super().__setattr__(attr, value)

   sys.modules[__name__].__class__ = VerboseModule

참고:

  모듈 "__getattr__" 정의와 모듈 "__class__" 설정은 어트리뷰트 액세스
  구문을 사용하는 조회에만 영향을 미칩니다 -- 모듈 전역에 대한 직접적
  인 액세스(모듈 내의 코드에 의한 액세스이거나 모듈의 전역 딕셔너리에
  대한 참조를 거치거나)는 영향받지 않습니다.

버전 3.5에서 변경: 이제 "__class__" 모듈 어트리뷰트가 쓰기 가능합니다.

Added in version 3.7: "__getattr__" 과 "__dir__" 모듈 어트리뷰트.

더 보기:

  **PEP 562** - 모듈 __getattr__ 과 __dir__
     모듈에 대한 "__getattr__" 과 "__dir__" 함수를 설명합니다.


3.3.2.2. 디스크립터 구현하기
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The following methods only apply when an instance of the class
containing the method (a so-called *descriptor* class) appears in an
*owner* class (the descriptor must be in either the owner's class
dictionary or in the class dictionary for one of its parents).  In the
examples below, "the attribute" refers to the attribute whose name is
the key of the property in the owner class' "__dict__".  The "object"
class itself does not implement any of these protocols.

object.__get__(self, instance, owner=None)

   소유자 클래스(클래스 어트리뷰트 액세스) 나 그 클래스의 인스턴스(인
   스턴스 어트리뷰트 액세스)의 어트리뷰트를 취하려고 할 때 호출됩니다.
   선택적 *owner* 인자는 소유자 클래스입니다. 반면에 *instance* 는 어
   트리뷰트 참조가 일어나고 있는 인스턴스이거나, 어트리뷰트가 *owner*
   를 통해 액세스 되는 경우 *None* 입니다.

   이 메서드는 계산된 어트리뷰트 값을 돌려주거나 "AttributeError" 예외
   를 일으켜야 합니다.

   **PEP 252**는 "__get__()"이 하나나 두 개의 인자를 갖는 콜러블이라고
   지정합니다. 파이썬 자신의 내장 디스크립터는 이 명세를 지원합니다;
   그러나, 일부 제삼자 도구에는 두 인수를 모두 요구하는 디스크립터가
   있을 수 있습니다. 파이썬 자신의 "__getattribute__()" 구현은 필요한
   지와 관계없이 항상 두 인자를 모두 전달합니다.

object.__set__(self, instance, value)

   소유자 클래스의 인스턴스 *instance* 의 어트리뷰트를 새 값 *value*
   로 설정할 때 호출됩니다.

   "__set__()"이나 "__delete__()"를 추가하면 디스크립터 유형이 "데이터
   디스크립터(data descriptor)"로 변경됨에 유의하십시오. 자세한 내용은
   디스크립터 호출하기를 참조하십시오.

object.__delete__(self, instance)

   소유자 클래스의 인스턴스 *instance* 의 어트리뷰트를 삭제할 때 호출
   됩니다.

Instances of descriptors may also have the "__objclass__" attribute
present:

object.__objclass__

   The attribute "__objclass__" is interpreted by the "inspect" module
   as specifying the class where this object was defined (setting this
   appropriately can assist in runtime introspection of dynamic class
   attributes). For callables, it may indicate that an instance of the
   given type (or a subclass) is expected or required as the first
   positional argument (for example, CPython sets this attribute for
   unbound methods that are implemented in C).


3.3.2.3. 디스크립터 호출하기
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In general, a descriptor is an object attribute with "binding
behavior", one whose attribute access has been overridden by methods
in the descriptor protocol:  "__get__()", "__set__()", and
"__delete__()". If any of those methods are defined for an object, it
is said to be a descriptor.

어트리뷰트 액세스의 기본 동작은 객체의 딕셔너리에서 어트리뷰트를 읽고,
쓰고, 삭제하는 것입니다. 예를 들어 "a.x" 는 "a.__dict__['x']" 에서 시
작해서 "type(a).__dict__['x']" 를 거쳐 "type(a)" 의 메타 클래스를 제외
한 베이스 클래스들을 거쳐 가는 일련의 조회로 구성됩니다.

그러나, 만약 조회한 값이 디스크립터 메서드를 구현한 객체면, 파이썬은
기본 동작 대신에 디스크립터 메서드를 호출할 수 있습니다. 우선순위 목록
의 어느 위치에서 이런 일이 일어나는지는 어떤 디스크립터 메서드가 정의
되어 있고 어떤 식으로 호출되는지에 따라 다릅니다.

디스크립터 호출의 시작점은 결합(binding)입니다, "a.x". 어떻게 인자들이
조합되는지는 "a" 에 따라 다릅니다:

직접 호출
   가장 간단하면서도 가장 덜 사용되는 호출은 사용자의 코드가 디스크립
   터 메서드를 직접 호출할 때입니다: "x.__get__(a)"

인스턴스 결합
   객체 인스턴스에 결합하면, "a.x" 는 이런 호출로 변환됩니다:
   "type(a).__dict__['x'].__get__(a, type(a))".

클래스 결합
   클래스에 결합하면, "A.x" 는 이런 호출로 변환됩니다:
   "A.__dict__['x'].__get__(None, A)".

Super 결합
   A dotted lookup such as "super(A, a).x" searches
   "a.__class__.__mro__" for a base class "B" following "A" and then
   returns "B.__dict__['x'].__get__(a, A)".  If not a descriptor, "x"
   is returned unchanged.

For instance bindings, the precedence of descriptor invocation depends
on which descriptor methods are defined.  A descriptor can define any
combination of "__get__()", "__set__()" and "__delete__()".  If it
does not define "__get__()", then accessing the attribute will return
the descriptor object itself unless there is a value in the object's
instance dictionary.  If the descriptor defines "__set__()" and/or
"__delete__()", it is a data descriptor; if it defines neither, it is
a non-data descriptor.  Normally, data descriptors define both
"__get__()" and "__set__()", while non-data descriptors have just the
"__get__()" method.  Data descriptors with "__get__()" and "__set__()"
(and/or "__delete__()") defined always override a redefinition in an
instance dictionary.  In contrast, non-data descriptors can be
overridden by instances.

Python methods (including those decorated with "@staticmethod" and
"@classmethod") are implemented as non-data descriptors.  Accordingly,
instances can redefine and override methods.  This allows individual
instances to acquire behaviors that differ from other instances of the
same class.

"property()" 함수는 데이터 디스크립터로 구현됩니다. 이 때문에, 인스턴
스는 프로퍼티(property)의 동작을 변경할 수 없습니다.


3.3.2.4. __slots__
~~~~~~~~~~~~~~~~~~

*__slots__* allow us to explicitly declare data members (like
properties) and deny the creation of "__dict__" and *__weakref__*
(unless explicitly declared in *__slots__* or available in a parent.)

The space saved over using "__dict__" can be significant. Attribute
lookup speed can be significantly improved as well.

object.__slots__

   This class variable can be assigned a string, iterable, or sequence
   of strings with variable names used by instances.  *__slots__*
   reserves space for the declared variables and prevents the
   automatic creation of "__dict__" and *__weakref__* for each
   instance.

Notes on using *__slots__*:

* When inheriting from a class without *__slots__*, the "__dict__" and
  *__weakref__* attribute of the instances will always be accessible.

* Without a "__dict__" variable, instances cannot be assigned new
  variables not listed in the *__slots__* definition.  Attempts to
  assign to an unlisted variable name raises "AttributeError". If
  dynamic assignment of new variables is desired, then add
  "'__dict__'" to the sequence of strings in the *__slots__*
  declaration.

* Without a *__weakref__* variable for each instance, classes defining
  *__slots__* do not support "weak references" to its instances. If
  weak reference support is needed, then add "'__weakref__'" to the
  sequence of strings in the *__slots__* declaration.

* *__slots__* are implemented at the class level by creating
  descriptors for each variable name.  As a result, class attributes
  cannot be used to set default values for instance variables defined
  by *__slots__*; otherwise, the class attribute would overwrite the
  descriptor assignment.

* The action of a *__slots__* declaration is not limited to the class
  where it is defined.  *__slots__* declared in parents are available
  in child classes. However, instances of a child subclass will get a
  "__dict__" and *__weakref__* unless the subclass also defines
  *__slots__* (which should only contain names of any *additional*
  slots).

* 클래스가 베이스 클래스의 *__slots__* 에 정의된 이름과 같은 이름의 변
  수를 *__slots__* 에 선언한다면, 베이스 클래스가 정의한 변수는 액세스
  할 수 없는 상태가 됩니다(베이스 클래스로부터 디스크립터를 직접 조회
  하는 경우는 예외다). 이것은 프로그램을 정의되지 않은 상태로 보내게
  됩니다. 미래에는, 이를 방지하기 위한 검사가 추가될 것입니다.

* "TypeError" will be raised if nonempty *__slots__* are defined for a
  class derived from a ""variable-length" built-in type" such as
  "int", "bytes", and "tuple".

* Any non-string *iterable* may be assigned to *__slots__*.

* If a "dictionary" is used to assign *__slots__*, the dictionary keys
  will be used as the slot names. The values of the dictionary can be
  used to provide per-attribute docstrings that will be recognised by
  "inspect.getdoc()" and displayed in the output of "help()".

* "__class__" assignment works only if both classes have the same
  *__slots__*.

* Multiple inheritance with multiple slotted parent classes can be
  used, but only one parent is allowed to have attributes created by
  slots (the other bases must have empty slot layouts) - violations
  raise "TypeError".

* If an *iterator* is used for *__slots__* then a *descriptor* is
  created for each of the iterator's values. However, the *__slots__*
  attribute will be an empty iterator.


3.3.3. 클래스 생성 커스터마이제이션
-----------------------------------

Whenever a class inherits from another class, "__init_subclass__()" is
called on the parent class. This way, it is possible to write classes
which change the behavior of subclasses. This is closely related to
class decorators, but where class decorators only affect the specific
class they're applied to, "__init_subclass__" solely applies to future
subclasses of the class defining the method.

classmethod object.__init_subclass__(cls)

   이 메서드는 포함하는 클래스의 서브 클래스가 만들어질 때마다 호출됩
   니다. *cls* 는 새 서브 클래스입니다. 만약 일반적인 인스턴스 메서드
   로 정의되면, 이 메서드는 묵시적으로 클래스 메서드로 변경됩니다.

   Keyword arguments which are given to a new class are passed to the
   parent class's "__init_subclass__". For compatibility with other
   classes using "__init_subclass__", one should take out the needed
   keyword arguments and pass the others over to the base class, as
   in:

      class Philosopher:
          def __init_subclass__(cls, /, default_name, **kwargs):
              super().__init_subclass__(**kwargs)
              cls.default_name = default_name

      class AustralianPhilosopher(Philosopher, default_name="Bruce"):
          pass

   기본 구현 "object.__init_subclass__" 는 아무 일도 하지 않지만, 인자
   가 포함되어 호출되면 예외를 발생시킵니다.

   참고:

     메타 클래스 힌트 "metaclass" 는 나머지 형 절차에 의해 소비되고,
     "__init_subclass__" 로 전달되지 않습니다. 실제 메타 클래스 (명시
     적인 힌트 대신에) 는 "type(cls)" 로 액세스할 수 있습니다.

   Added in version 3.6.

When a class is created, "type.__new__()" scans the class variables
and makes callbacks to those with a "__set_name__()" hook.

object.__set_name__(self, owner, name)

   Automatically called at the time the owning class *owner* is
   created. The object has been assigned to *name* in that class:

      class A:
          x = C()  # Automatically calls: x.__set_name__(A, 'x')

   If the class variable is assigned after the class is created,
   "__set_name__()" will not be called automatically. If needed,
   "__set_name__()" can be called directly:

      class A:
         pass

      c = C()
      A.x = c                  # The hook is not called
      c.__set_name__(A, 'x')   # Manually invoke the hook

   더 자세한 내용은 클래스 객체 만들기 을 참고하십시오.

   Added in version 3.6.


3.3.3.1. 메타 클래스
~~~~~~~~~~~~~~~~~~~~

기본적으로, 클래스는 "type()" 을 사용해서 만들어집니다. 클래스의 바디
는 새 이름 공간에서 실행되고, 클래스 이름은 "type(name, bases,
namespace)" 의 결과에 지역적으로 연결됩니다.

클래스를 만드는 과정은 클래스 정의 줄에 "metaclass" 키워드 인자를 전달
하거나, 그런 인자를 포함한 이미 존재하는 클래스를 계승함으로써 커스터
마이즈될 수 있습니다. 다음 예에서, "MyClass" 와 "MySubclass" 는 모두
"Meta" 의 인스턴스입니다.

   class Meta(type):
       pass

   class MyClass(metaclass=Meta):
       pass

   class MySubclass(MyClass):
       pass

클래스 정의에서 지정된 다른 키워드 인자들은 아래에서 설명되는 모든 메
타 클래스 연산들로 전달됩니다.

클래스 정의가 실행될 때, 다음과 같은 단계가 수행됩니다.:

* MRO 항목이 결정됩니다;

* 적절한 메타 클래스가 결정됩니다;

* 클래스 이름 공간이 준비됩니다;

* 클래스 바디가 실행됩니다;

* 클래스 객체가 만들어집니다.


3.3.3.2. MRO 항목 결정하기
~~~~~~~~~~~~~~~~~~~~~~~~~~

object.__mro_entries__(self, bases)

   If a base that appears in a class definition is not an instance of
   "type", then an "__mro_entries__()" method is searched on the base.
   If an "__mro_entries__()" method is found, the base is substituted
   with the result of a call to "__mro_entries__()" when creating the
   class. The method is called with the original bases tuple passed to
   the *bases* parameter, and must return a tuple of classes that will
   be used instead of the base. The returned tuple may be empty: in
   these cases, the original base is ignored.

더 보기:

  "types.resolve_bases()"
     Dynamically resolve bases that are not instances of "type".

  "types.get_original_bases()"
     Retrieve a class's "original bases" prior to modifications by
     "__mro_entries__()".

  **PEP 560**
     Core support for typing module and generic types.


3.3.3.3. 적절한 메타 클래스 선택하기
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

클래스 정의의 적절한 메타 클래스는 다음과 같이 결정됩니다:

* 베이스와 명시적인 메타 클래스를 주지 않는 경우 "type()" 이 사용됩니
  다;

* 명시적인 메타 클래스가 지정되고, 그것이 "type()" 의 인스턴스가 *아니
  면*, 그것을 메타 클래스로 사용합니다;

* "type()" 의 인스턴스가 명시적인 메타 클래스로 주어지거나, 베이스가
  정의되었으면, 가장 많이 파생된 메타 클래스가 사용됩니다.

가장 많이 파생된 메타 클래스는 명시적으로 지정된 메타 클래스(있다면)와
지정된 모든 베이스 클래스들의 메타 클래스들(즉, "type(cls)") 중에서 선
택됩니다. 가장 많이 파생된 메타 클래스는 이들 *모두* 의 서브 타입
(subtype)입니다. 만약 어느 것도 이 조건을 만족하지 못한다면, 클래스 정
의는 "TypeError" 를 발생시키며 실패합니다.


3.3.3.4. 클래스 이름 공간 준비하기
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Once the appropriate metaclass has been identified, then the class
namespace is prepared. If the metaclass has a "__prepare__" attribute,
it is called as "namespace = metaclass.__prepare__(name, bases,
**kwds)" (where the additional keyword arguments, if any, come from
the class definition). The "__prepare__" method should be implemented
as a "classmethod". The namespace returned by "__prepare__" is passed
in to "__new__", but when the final class object is created the
namespace is copied into a new "dict".

만약 메타 클래스에 "__prepare__" 어트리뷰트가 없다면, 클래스 이름 공간
은 빈 순서 있는 매핑으로 초기화됩니다.

더 보기:

  **PEP 3115** - 파이썬 3000 에서의 메타 클래스
     "__prepare__" 이름 공간 훅을 도입했습니다


3.3.3.5. 클래스 바디 실행하기
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

클래스 바디는 (대략) "exec(body, globals(), namespace)" 과같이 실행됩
니다. 일반적인 "exec()" 호출과 주된 차이점은 클래스 정의가 함수 내부에
서 이루어질 때 어휘 스코핑(lexical scoping) 이 클래스 바디(모든 메서드
들을 포함해서)로 하여금 현재와 외부 스코프에 있는 이름들을 참조하도록
허락한다는 것입니다.

하지만, 클래스 정의가 함수 내부에서 이루어질 때조차도, 클래스 내부에서
정의된 메서드들은 클래스 스코프에서 정의된 이름들을 볼 수 없습니다. 클
래스 변수는 인스턴스나 클래스 메서드의 첫 번째 매개변수를 통해 액세스
하거나 다음 섹션에서 설명하는 묵시적으로 어휘 스코핑된 "__class__" 참
조를 통해야 합니다.


3.3.3.6. 클래스 객체 만들기
~~~~~~~~~~~~~~~~~~~~~~~~~~~

일단 클래스 이름 공간이 클래스 바디를 실행함으로써 채워지면, 클래스 객
체가 "metaclass(name, bases, namespace, **kwds)" 을 통해 만들어집니다(
여기에서 전달되는 추가적인 키워드 인자들은 "__prepare__" 에 전달된 것
들과 같습니다).

이 클래스 객체는 "super()" 에 인자를 주지 않는 경우 참조되는 것입니다.
"__class__" 는 클래스 바디의 메서드들 중 어느 하나라도 "__class__" 나
"super" 를 참조할 경우 컴파일러에 의해 만들어지는 묵시적인 클로저
(closure) 참조입니다. 이것은 인자 없는 형태의 "super()" 가 어휘 스코핑
기반으로 현재 정의되고 있는 클래스를 올바르게 찾을 수 있도록 합니다.
반면에 현재의 호출에 사용된 클래스나 인스턴스는 메서드로 전달된 첫 번
째 인자에 기초해서 식별됩니다.

CPython 3.6 이상에서, "__class__" 셀(cell)은 클래스 이름 공간의
"__classcell__" 엔트리로 메타 클래스에 전달됩니다. 만약 존재한다면, 이
것은 클래스가 올바르게 초기화되기 위해 "type.__new__" 호출까지 거슬러
서 전파되어야 합니다. 이렇게 하지 못하면 파이썬 3.8 에서는
"RuntimeError"로 이어질 것입니다.

When using the default metaclass "type", or any metaclass that
ultimately calls "type.__new__", the following additional
customization steps are invoked after creating the class object:

1. The "type.__new__" method collects all of the attributes in the
   class namespace that define a "__set_name__()" method;

2. Those "__set_name__" methods are called with the class being
   defined and the assigned name of that particular attribute;

3. The "__init_subclass__()" hook is called on the immediate parent of
   the new class in its method resolution order.

클래스 객체가 만들어진 후에, 클래스 정의에 포함된 클래스 데코레이터들
에게 (있다면) 클래스를 전달하고, 그 결과를 클래스가 정의되는 지역 이름
공간에 연결합니다.

When a new class is created by "type.__new__", the object provided as
the namespace parameter is copied to a new ordered mapping and the
original object is discarded. The new copy is wrapped in a read-only
proxy, which becomes the "__dict__" attribute of the class object.

더 보기:

  **PEP 3135** - 새 super
     묵시적인 __class__ 클로저 참조를 설명합니다


3.3.3.7. 메타 클래스의 용도
~~~~~~~~~~~~~~~~~~~~~~~~~~~

메타 클래스의 잠재적인 용도에는 한계가 없습니다. 탐색 된 몇 가지 아이
디어들에는 enum, 로깅, 인터페이스 검사, 자동화된 위임(automatic
delegation), 자동화된 프로퍼티(properety) 생성, 프락시(proxy), 프레임
웍(framework), 자동화된 자원 로킹/동기화(automatic resource
locking/synchronization) 등이 있습니다.


3.3.4. 인스턴스 및 서브 클래스 검사 커스터마이제이션
----------------------------------------------------

다음 메서드들은 "isinstance()" 와 "issubclass()" 내장 함수들의 기본 동
작을 재정의하는 데 사용됩니다.

특히, 메타 클래스 "abc.ABCMeta" 는 추상 베이스 클래스(Abstract Base
Class, ABC)를 다른 ABC를 포함한 임의의 클래스나 형(내장형을 포함합니다
)에 "가상 베이스 클래스(virtual base class)"로 추가할 수 있게 하려고
이 메서드들을 구현합니다.

type.__instancecheck__(self, instance)

   *instance* 가 (직접적이거나 간접적으로) *class* 의 인스턴스로 취급
   될 수 있으면 참을 돌려줍니다. 만약 정의되면, "isinstance(instance,
   class)" 를 구현하기 위해 호출됩니다.

type.__subclasscheck__(self, subclass)

   *subclass* 가 (직접적이거나 간접적으로) *class* 의 서브 클래스로 취
   급될 수 있으면 참을 돌려줍니다. 만약 정의되면,
   "issubclass(subclass, class)" 를 구현하기 위해 호출됩니다.

이 메서드들은 클래스의 형(메타 클래스)에서 조회된다는 것에 주의해야 합
니다. 실제 클래스에서 클래스 메서드로 정의될 수 없습니다. 이것은 인스
턴스에 대해 호출되는 특수 메서드들의 조회와 일관성 있습니다. 이 경우
인스턴스는 클래스 자체다.

더 보기:

  **PEP 3119** - 추상 베이스 클래스의 도입
     Includes the specification for customizing "isinstance()" and
     "issubclass()" behavior through "__instancecheck__()" and
     "__subclasscheck__()", with motivation for this functionality in
     the context of adding Abstract Base Classes (see the "abc"
     module) to the language.


3.3.5. 제네릭 형 흉내 내기
--------------------------

When using *type annotations*, it is often useful to *parameterize* a
*generic type* using Python's square-brackets notation. For example,
the annotation "list[int]" might be used to signify a "list" in which
all the elements are of type "int".

더 보기:

  **PEP 484** - Type Hints
     Introducing Python's framework for type annotations

  Generic Alias Types
     Documentation for objects representing parameterized generic
     classes

  제네릭, user-defined generics and "typing.Generic"
     Documentation on how to implement generic classes that can be
     parameterized at runtime and understood by static type-checkers.

A class can *generally* only be parameterized if it defines the
special class method "__class_getitem__()".

classmethod object.__class_getitem__(cls, key)

   *key* 에 있는 형 인자에 의한 제네릭 클래스의 특수화를 나타내는 객체
   를 돌려줍니다.

   When defined on a class, "__class_getitem__()" is automatically a
   class method. As such, there is no need for it to be decorated with
   "@classmethod" when it is defined.


3.3.5.1. The purpose of *__class_getitem__*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The purpose of "__class_getitem__()" is to allow runtime
parameterization of standard-library generic classes in order to more
easily apply *type hints* to these classes.

To implement custom generic classes that can be parameterized at
runtime and understood by static type-checkers, users should either
inherit from a standard library class that already implements
"__class_getitem__()", or inherit from "typing.Generic", which has its
own implementation of "__class_getitem__()".

Custom implementations of "__class_getitem__()" on classes defined
outside of the standard library may not be understood by third-party
type-checkers such as mypy. Using "__class_getitem__()" on any class
for purposes other than type hinting is discouraged.


3.3.5.2. *__class_getitem__* versus *__getitem__*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Usually, the subscription of an object using square brackets will call
the "__getitem__()" instance method defined on the object's class.
However, if the object being subscribed is itself a class, the class
method "__class_getitem__()" may be called instead.
"__class_getitem__()" should return a GenericAlias object if it is
properly defined.

Presented with the *expression* "obj[x]", the Python interpreter
follows something like the following process to decide whether
"__getitem__()" or "__class_getitem__()" should be called:

   from inspect import isclass

   def subscribe(obj, x):
       """Return the result of the expression 'obj[x]'"""

       class_of_obj = type(obj)

       # If the class of obj defines __getitem__,
       # call class_of_obj.__getitem__(obj, x)
       if hasattr(class_of_obj, '__getitem__'):
           return class_of_obj.__getitem__(obj, x)

       # Else, if obj is a class and defines __class_getitem__,
       # call obj.__class_getitem__(x)
       elif isclass(obj) and hasattr(obj, '__class_getitem__'):
           return obj.__class_getitem__(x)

       # Else, raise an exception
       else:
           raise TypeError(
               f"'{class_of_obj.__name__}' object is not subscriptable"
           )

In Python, all classes are themselves instances of other classes. The
class of a class is known as that class's *metaclass*, and most
classes have the "type" class as their metaclass. "type" does not
define "__getitem__()", meaning that expressions such as "list[int]",
"dict[str, float]" and "tuple[str, bytes]" all result in
"__class_getitem__()" being called:

   >>> # list has class "type" as its metaclass, like most classes:
   >>> type(list)
   <class 'type'>
   >>> type(dict) == type(list) == type(tuple) == type(str) == type(bytes)
   True
   >>> # "list[int]" calls "list.__class_getitem__(int)"
   >>> list[int]
   list[int]
   >>> # list.__class_getitem__ returns a GenericAlias object:
   >>> type(list[int])
   <class 'types.GenericAlias'>

However, if a class has a custom metaclass that defines
"__getitem__()", subscribing the class may result in different
behaviour. An example of this can be found in the "enum" module:

   >>> from enum import Enum
   >>> class Menu(Enum):
   ...     """A breakfast menu"""
   ...     SPAM = 'spam'
   ...     BACON = 'bacon'
   ...
   >>> # Enum classes have a custom metaclass:
   >>> type(Menu)
   <class 'enum.EnumMeta'>
   >>> # EnumMeta defines __getitem__,
   >>> # so __class_getitem__ is not called,
   >>> # and the result is not a GenericAlias object:
   >>> Menu['SPAM']
   <Menu.SPAM: 'spam'>
   >>> type(Menu['SPAM'])
   <enum 'Menu'>

더 보기:

  **PEP 560** - Core Support for typing module and generic types
     Introducing "__class_getitem__()", and outlining when a
     subscription results in "__class_getitem__()" being called
     instead of "__getitem__()"


3.3.6. 콜러블 객체 흉내 내기
----------------------------

object.__call__(self[, args...])

   Called when the instance is "called" as a function; if this method
   is defined, "x(arg1, arg2, ...)" roughly translates to
   "type(x).__call__(x, arg1, ...)". The "object" class itself does
   not provide this method.


3.3.7. 컨테이너형 흉내 내기
---------------------------

The following methods can be defined to implement container objects.
None of them are provided by the "object" class itself. Containers
usually are *sequences* (such as "lists" or "tuples") or *mappings*
(like *dictionaries*), but can represent other containers as well.
The first set of methods is used either to emulate a sequence or to
emulate a mapping; the difference is that for a sequence, the
allowable keys should be the integers *k* for which "0 <= k < N" where
*N* is the length of the sequence, or "slice" objects, which define a
range of items.  It is also recommended that mappings provide the
methods "keys()", "values()", "items()", "get()", "clear()",
"setdefault()", "pop()", "popitem()", "copy()", and "update()"
behaving similar to those for Python's standard "dictionary" objects.
The "collections.abc" module provides a "MutableMapping" *abstract
base class* to help create those methods from a base set of
"__getitem__()", "__setitem__()", "__delitem__()", and "keys()".

Mutable sequences should provide methods "append()", "clear()",
"count()", "extend()", "index()", "insert()", "pop()", "remove()", and
"reverse()", like Python standard "list" objects. Finally, sequence
types should implement addition (meaning concatenation) and
multiplication (meaning repetition) by defining the methods
"__add__()", "__radd__()", "__iadd__()", "__mul__()", "__rmul__()" and
"__imul__()" described below; they should not define other numerical
operators.

It is recommended that both mappings and sequences implement the
"__contains__()" method to allow efficient use of the "in" operator;
for mappings, "in" should search the mapping's keys; for sequences, it
should search through the values.  It is further recommended that both
mappings and sequences implement the "__iter__()" method to allow
efficient iteration through the container; for mappings, "__iter__()"
should iterate through the object's keys; for sequences, it should
iterate through the values.

object.__len__(self)

   Called to implement the built-in function "len()".  Should return
   the length of the object, an integer ">=" 0.  Also, an object that
   doesn't define a "__bool__()" method and whose "__len__()" method
   returns zero is considered to be false in a Boolean context.

   **CPython 구현 상세:** In CPython, the length is required to be at
   most "sys.maxsize". If the length is larger than "sys.maxsize" some
   features (such as "len()") may raise "OverflowError".  To prevent
   raising "OverflowError" by truth value testing, an object must
   define a "__bool__()" method.

object.__length_hint__(self)

   Called to implement "operator.length_hint()". Should return an
   estimated length for the object (which may be greater or less than
   the actual length). The length must be an integer ">=" 0. The
   return value may also be "NotImplemented", which is treated the
   same as if the "__length_hint__" method didn't exist at all. This
   method is purely an optimization and is never required for
   correctness.

   Added in version 3.4.

참고:

  슬라이싱은 전적으로 다음에 나오는 세 메서드들에의해 수행됩니다

     a[1:2] = b

  과 같은 호출은

     a[slice(1, 2, None)] = b

  로 번역되고, 다른 형태도 마찬가지입니다. 빠진 슬라이스 항목은 항상
  "None" 으로 채워집니다.

object.__getitem__(self, key)

   Called to implement evaluation of "self[key]". For *sequence*
   types, the accepted keys should be integers. Optionally, they may
   support "slice" objects as well.  Negative index support is also
   optional. If *key* is of an inappropriate type, "TypeError" may be
   raised; if *key* is a value outside the set of indexes for the
   sequence (after any special interpretation of negative values),
   "IndexError" should be raised. For *mapping* types, if *key* is
   missing (not in the container), "KeyError" should be raised.

   참고:

     "for" 루프는 시퀀스의 끝을 올바로 감지하기 위해, 잘못된 인덱스에
     대해 "IndexError" 가 일어날 것으로 기대하고 있습니다.

   참고:

     When subscripting a *class*, the special class method
     "__class_getitem__()" may be called instead of "__getitem__()".
     See __class_getitem__ versus __getitem__ for more details.

object.__setitem__(self, key, value)

   "self[key]" 로의 대입을 구현하기 위해 호출됩니다. "__getitem__()"
   과 같은 주의가 필요합니다. 매핑의 경우에는, 객체가 키에 대해 값의
   변경이나 새 키의 추가를 허락할 경우, 시퀀스의 경우는 항목이 교체될
   수 있을 때만 구현되어야 합니다. 잘못된 *key* 값의 경우는
   "__getitem__()" 에서와 같은 예외를 일으켜야 합니다.

object.__delitem__(self, key)

   "self[key]" 의 삭제를 구현하기 위해 호출됩니다. "__getitem__()" 과
   같은 주의가 필요합니다. 매핑의 경우에는, 객체가 키의 삭제를 허락할
   경우, 시퀀스의 경우는 항목이 시퀀스로부터 제거될 수 있을 때만 구현
   되어야 합니다. 잘못된 *key* 값의 경우는 "__getitem__()" 에서와 같은
   예외를 일으켜야 합니다.

object.__missing__(self, key)

   "dict"."__getitem__()" 이 dict 서브 클래스에서 키가 딕셔너리에 없으
   면 "self[key]" 를 구현하기 위해 호출합니다.

object.__iter__(self)

   This method is called when an *iterator* is required for a
   container. This method should return a new iterator object that can
   iterate over all the objects in the container.  For mappings, it
   should iterate over the keys of the container.

object.__reversed__(self)

   "reversed()" 내장 함수가 역 이터레이션(reverse iteration)을 구현하
   기 위해 (있다면) 호출합니다. 컨테이너에 있는 객체들을 역 순으로 탐
   색하는 새 이터레이터 객체를 돌려줘야 합니다.

   "__reversed__()" 메서드가 제공되지 않으면, "reversed()" 내장함수는
   시퀀스 프로토콜("__len__()" 과 "__getitem__()")을 대안으로 사용합니
   다. 시퀀스 프로토콜을 지원하는 객체들은 "reversed()" 가 제공하는 것
   보다 더 효율적인 구현을 제공할 수 있을 때만 "__reversed__()" 를 제
   공해야 합니다.

멤버십 검사 연산자들("in" 과 "not in") 은 보통 컨테이너에 대한 이터레
이션으로 구현됩니다. 하지만, 컨테이너 객체는 더 효율적인 구현을 다음과
같은 특수 메서드를 통해 제공할 수 있습니다. 이 경우 객체는 이터러블일
필요도 없습니다.

object.__contains__(self, item)

   멤버십 검사 연산자를 구현하기 위해 호출됩니다. *item* 이 *self* 에
   있으면 참을, 그렇지 않으면 거짓을 돌려줘야 합니다. 매핑 객체의 경우
   , 키-값 쌍이 아니라 매핑의 키가 고려되어야 합니다.

   "__contains__()" 를 정의하지 않는 객체의 경우, 멤버십 검사는 먼저
   "__iter__()" 를 통한 이터레이션을 시도한 후, "__getitem__()" 을 통
   한 낡은 시퀀스 이터레이션 프로토콜을 시도합니다. 언어 레퍼런스의 이
   절을 참고하십시오.


3.3.8. 숫자 형 흉내 내기
------------------------

숫자 형을 흉내 내기 위해 다음과 같은 메서드들을 정의할 수 있습니다. 구
현되는 특별한 종류의 숫자에 의해 지원되지 않는 연산들(예를 들어, 정수
가 아닌 숫자들에 대한 비트 연산들)에 대응하는 메서드들을 정의되지 않은
채로 남겨두어야 합니다.

object.__add__(self, other)
object.__sub__(self, other)
object.__mul__(self, other)
object.__matmul__(self, other)
object.__truediv__(self, other)
object.__floordiv__(self, other)
object.__mod__(self, other)
object.__divmod__(self, other)
object.__pow__(self, other[, modulo])
object.__lshift__(self, other)
object.__rshift__(self, other)
object.__and__(self, other)
object.__xor__(self, other)
object.__or__(self, other)

   These methods are called to implement the binary arithmetic
   operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
   "pow()", "**", "<<", ">>", "&", "^", "|").  For instance, to
   evaluate the expression "x + y", where *x* is an instance of a
   class that has an "__add__()" method, "type(x).__add__(x, y)" is
   called.  The "__divmod__()" method should be the equivalent to
   using "__floordiv__()" and "__mod__()"; it should not be related to
   "__truediv__()".  Note that "__pow__()" should be defined to accept
   an optional third argument if the three-argument version of the
   built-in "pow()" function is to be supported.

   If one of those methods does not support the operation with the
   supplied arguments, it should return "NotImplemented".

object.__radd__(self, other)
object.__rsub__(self, other)
object.__rmul__(self, other)
object.__rmatmul__(self, other)
object.__rtruediv__(self, other)
object.__rfloordiv__(self, other)
object.__rmod__(self, other)
object.__rdivmod__(self, other)
object.__rpow__(self, other[, modulo])
object.__rlshift__(self, other)
object.__rrshift__(self, other)
object.__rand__(self, other)
object.__rxor__(self, other)
object.__ror__(self, other)

   These methods are called to implement the binary arithmetic
   operations ("+", "-", "*", "@", "/", "//", "%", "divmod()",
   "pow()", "**", "<<", ">>", "&", "^", "|") with reflected (swapped)
   operands.  These functions are only called if the operands are of
   different types, when the left operand does not support the
   corresponding operation [3], or the right operand's class is
   derived from the left operand's class. [4] For instance, to
   evaluate the expression "x - y", where *y* is an instance of a
   class that has an "__rsub__()" method, "type(y).__rsub__(y, x)" is
   called if "type(x).__sub__(x, y)" returns "NotImplemented" or
   "type(y)" is a subclass of "type(x)". [5]

   Note that "__rpow__()" should be defined to accept an optional
   third argument if the three-argument version of the built-in
   "pow()" function is to be supported.

   버전 3.14에서 변경: Three-argument "pow()" now try calling
   "__rpow__()" if necessary. Previously it was only called in two-
   argument "pow()" and the binary power operator.

   참고:

     만약 오른쪽 피연산자의 형이 왼쪽 피연산자의 형의 서브 클래스이고,
     그 서브 클래스가 연산의 뒤집힌 메서드의 다른 구현을 제공하면, 이
     메서드가 왼쪽 연산자의 뒤집히지 않은 메서드보다 먼저 호출됩니다.
     이 동작은 서브 클래스가 조상들의 연산을 재정의할 수 있도록 합니다
     .

object.__iadd__(self, other)
object.__isub__(self, other)
object.__imul__(self, other)
object.__imatmul__(self, other)
object.__itruediv__(self, other)
object.__ifloordiv__(self, other)
object.__imod__(self, other)
object.__ipow__(self, other[, modulo])
object.__ilshift__(self, other)
object.__irshift__(self, other)
object.__iand__(self, other)
object.__ixor__(self, other)
object.__ior__(self, other)

   These methods are called to implement the augmented arithmetic
   assignments ("+=", "-=", "*=", "@=", "/=", "//=", "%=", "**=",
   "<<=", ">>=", "&=", "^=", "|=").  These methods should attempt to
   do the operation in-place (modifying *self*) and return the result
   (which could be, but does not have to be, *self*).  If a specific
   method is not defined, or if that method returns "NotImplemented",
   the augmented assignment falls back to the normal methods.  For
   instance, if *x* is an instance of a class with an "__iadd__()"
   method, "x += y" is equivalent to "x = x.__iadd__(y)" . If
   "__iadd__()" does not exist, or if "x.__iadd__(y)" returns
   "NotImplemented", "x.__add__(y)" and "y.__radd__(x)" are
   considered, as with the evaluation of "x + y". In certain
   situations, augmented assignment can result in unexpected errors
   (see 덧셈은 작동하는데, 왜 a_tuple[i] += ['item']이 예외를 일으킵니
   까?), but this behavior is in fact part of the data model.

object.__neg__(self)
object.__pos__(self)
object.__abs__(self)
object.__invert__(self)

   일 항 산술 연산("-", "+", "abs()", "~")을 구현하기 위해 호출됩니다.

object.__complex__(self)
object.__int__(self)
object.__float__(self)

   내장 함수 "complex()", "int()", "float()"를 구현하기 위해 호출됩니
   다. 적절한 형의 값을 돌려줘야 합니다.

object.__index__(self)

   "operator.index()" 를 구현하기 위해 호출되고, 파이썬이 숫자 객체를
   정수 객체로 손실 없이 변환해야 할 때(슬라이싱이나 내장 "bin()",
   "hex()", "oct()" 함수들에서와같이)마다 호출됩니다. 이 메서드의 존재
   는 숫자 객체가 정수 형임을 가리킵니다. 반드시 정수를 돌려줘야 합니
   다.

   "__int__()", "__float__()" 및 "__complex__()"가 정의되어 있지 않으
   면, 해당 내장 함수 "int()", "float()" 및 "complex()"는
   "__index__()"를 사용합니다.

object.__round__(self[, ndigits])
object.__trunc__(self)
object.__floor__(self)
object.__ceil__(self)

   내장 함수 "round()"와 "math" 함수 "trunc()", "floor()", "ceil()" 을
   구현하기 위해 호출됩니다. *ndigits* 가 "__round__()" 로 전달되지 않
   는 한, 이 메서드들은 모두 "Integral" (보통 "int") 로 잘린 객체의 값
   을 돌려줘야 합니다.

   버전 3.14에서 변경: "int()" no longer delegates to the
   "__trunc__()" method.


3.3.9. with 문 컨텍스트 관리자
------------------------------

*컨텍스트 관리자 (context manager)* 는 "with" 문을 실행할 때 자리 잡는
실행 컨텍스트(context)를 정의하는 객체입니다. 코드 블록의 실행을 위해,
컨텍스트 관리자는 원하는 실행시간 컨텍스트로의 진입과 탈출을 처리합니
다. 컨텍스트 관리자는 보통 "with" 문(with 문 섹션에서 설명합니다)으로
시작되지만, 그들의 메서드를 호출해서 직접 사용할 수도 있습니다.

컨텍스트 관리자의 전형적인 용도에는 다양한 종류의 전역 상태(global
state)를 보관하고 복구하는 것, 자원을 로킹(locking)하고 언로킹
(unlocking)하는 것, 열린 파일을 닫는 것 등이 있습니다.

For more information on context managers, see 컨텍스트 관리자 형. The
"object" class itself does not provide the context manager methods.

object.__enter__(self)

   이 객체와 연관된 실행시간 컨텍스트에 진입합니다. "with" 문은 "as"
   절로 지정된 대상이 있다면, 이 메서드의 반환 값을 연결합니다.

object.__exit__(self, exc_type, exc_value, traceback)

   이 객체와 연관된 실행시간 컨텍스트를 종료합니다. 매개변수들은 컨텍
   스트에서 벗어나게 만든 예외를 기술합니다. 만약 컨텍스트가 예외 없이
   종료한다면, 세 인자 모두 "None" 이 됩니다.

   만약 예외가 제공되고, 메서드가 예외를 중지시키고 싶으면 (즉 확산하
   는 것을 막으려면) 참(true)을 돌려줘야 합니다. 그렇지 않으면 예외는
   이 메서드가 종료한 후에 계속 진행됩니다.

   Note that "__exit__()" methods should not reraise the passed-in
   exception; this is the caller's responsibility.

더 보기:

  **PEP 343** - "with" 문
     파이썬 "with" 문에 대한 규격, 배경, 예.


3.3.10. Customizing positional arguments in class pattern matching
------------------------------------------------------------------

When using a class name in a pattern, positional arguments in the
pattern are not allowed by default, i.e. "case MyClass(x, y)" is
typically invalid without special support in "MyClass". To be able to
use that kind of pattern, the class needs to define a *__match_args__*
attribute.

object.__match_args__

   This class variable can be assigned a tuple of strings. When this
   class is used in a class pattern with positional arguments, each
   positional argument will be converted into a keyword argument,
   using the corresponding value in *__match_args__* as the keyword.
   The absence of this attribute is equivalent to setting it to "()".

For example, if "MyClass.__match_args__" is "("left", "center",
"right")" that means that "case MyClass(x, y)" is equivalent to "case
MyClass(left=x, center=y)". Note that the number of arguments in the
pattern must be smaller than or equal to the number of elements in
*__match_args__*; if it is larger, the pattern match attempt will
raise a "TypeError".

Added in version 3.10.

더 보기:

  **PEP 634** - Structural Pattern Matching
     The specification for the Python "match" statement.


3.3.11. Emulating buffer types
------------------------------

The buffer protocol provides a way for Python objects to expose
efficient access to a low-level memory array. This protocol is
implemented by builtin types such as "bytes" and "memoryview", and
third-party libraries may define additional buffer types.

While buffer types are usually implemented in C, it is also possible
to implement the protocol in Python.

object.__buffer__(self, flags)

   Called when a buffer is requested from *self* (for example, by the
   "memoryview" constructor). The *flags* argument is an integer
   representing the kind of buffer requested, affecting for example
   whether the returned buffer is read-only or writable.
   "inspect.BufferFlags" provides a convenient way to interpret the
   flags. The method must return a "memoryview" object.

object.__release_buffer__(self, buffer)

   Called when a buffer is no longer needed. The *buffer* argument is
   a "memoryview" object that was previously returned by
   "__buffer__()". The method must release any resources associated
   with the buffer. This method should return "None". Buffer objects
   that do not need to perform any cleanup are not required to
   implement this method.

Added in version 3.12.

더 보기:

  **PEP 688** - Making the buffer protocol accessible in Python
     Introduces the Python "__buffer__" and "__release_buffer__"
     methods.

  "collections.abc.Buffer"
     ABC for buffer types.


3.3.12. Annotations
-------------------

Functions, classes, and modules may contain *annotations*, which are a
way to associate information (usually *type hints*) with a symbol.

object.__annotations__

   This attribute contains the annotations for an object. It is lazily
   evaluated, so accessing the attribute may execute arbitrary code
   and raise exceptions. If evaluation is successful, the attribute is
   set to a dictionary mapping from variable names to annotations.

   버전 3.14에서 변경: Annotations are now lazily evaluated.

object.__annotate__(format)

   An *annotate function*. Returns a new dictionary object mapping
   attribute/parameter names to their annotation values.

   Takes a format parameter specifying the format in which annotations
   values should be provided. It must be a member of the
   "annotationlib.Format" enum, or an integer with a value
   corresponding to a member of the enum.

   If an annotate function doesn't support the requested format, it
   must raise "NotImplementedError". Annotate functions must always
   support "VALUE" format; they must not raise "NotImplementedError()"
   when called with this format.

   When called with  "VALUE" format, an annotate function may raise
   "NameError"; it must not raise "NameError" when called requesting
   any other format.

   If an object does not have any annotations, "__annotate__" should
   preferably be set to "None" (it can’t be deleted), rather than set
   to a function that returns an empty dict.

   Added in version 3.14.

더 보기:

  **PEP 649** --- Deferred evaluation of annotation using descriptors
     Introduces lazy evaluation of annotations and the "__annotate__"
     function.


3.3.13. 특수 메서드 조회
------------------------

사용자 정의 클래스의 경우, 묵시적인 특수 메서드의 호출은 객체의 인스턴
스 딕셔너리가 아닌 객체의 형에 정의되어 있을 때만 올바르게 동작함이 보
장됩니다. 이런 동작은 다음과 같은 코드가 예외를 일으키는 원인입니다:

   >>> class C:
   ...     pass
   ...
   >>> c = C()
   >>> c.__len__ = lambda: 5
   >>> len(c)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: object of type 'C' has no len()

The rationale behind this behaviour lies with a number of special
methods such as "__hash__()" and "__repr__()" that are implemented by
all objects, including type objects. If the implicit lookup of these
methods used the conventional lookup process, they would fail when
invoked on the type object itself:

   >>> 1 .__hash__() == hash(1)
   True
   >>> int.__hash__() == hash(int)
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   TypeError: descriptor '__hash__' of 'int' object needs an argument

클래스의 연결되지 않은 메서드를 호출하려는 이런 식의 잘못된 시도는 종
종 '메타 클래스 혼란(metaclass confusion)' 이라고 불리고, 특수 메서드
를 조회할 때 인스턴스를 우회하는 방법으로 피할 수 있습니다.

   >>> type(1).__hash__(1) == hash(1)
   True
   >>> type(int).__hash__(int) == hash(int)
   True

In addition to bypassing any instance attributes in the interest of
correctness, implicit special method lookup generally also bypasses
the "__getattribute__()" method even of the object's metaclass:

   >>> class Meta(type):
   ...     def __getattribute__(*args):
   ...         print("Metaclass getattribute invoked")
   ...         return type.__getattribute__(*args)
   ...
   >>> class C(object, metaclass=Meta):
   ...     def __len__(self):
   ...         return 10
   ...     def __getattribute__(*args):
   ...         print("Class getattribute invoked")
   ...         return object.__getattribute__(*args)
   ...
   >>> c = C()
   >>> c.__len__()                 # Explicit lookup via instance
   Class getattribute invoked
   10
   >>> type(c).__len__(c)          # Explicit lookup via type
   Metaclass getattribute invoked
   10
   >>> len(c)                      # Implicit lookup
   10

Bypassing the "__getattribute__()" machinery in this fashion provides
significant scope for speed optimisations within the interpreter, at
the cost of some flexibility in the handling of special methods (the
special method *must* be set on the class object itself in order to be
consistently invoked by the interpreter).


3.4. 코루틴(Coroutines)
=======================


3.4.1. 어웨이터블 객체(Awaitable Objects)
-----------------------------------------

An *awaitable* object generally implements an "__await__()" method.
*Coroutine objects* returned from "async def" functions are awaitable.

참고:

  The *generator iterator* objects returned from generators decorated
  with "types.coroutine()" are also awaitable, but they do not
  implement "__await__()".

object.__await__(self)

   Must return an *iterator*.  Should be used to implement *awaitable*
   objects.  For instance, "asyncio.Future" implements this method to
   be compatible with the "await" expression. The "object" class
   itself is not awaitable and does not provide this method.

   참고:

     The language doesn't place any restriction on the type or value
     of the objects yielded by the iterator returned by "__await__",
     as this is specific to the implementation of the asynchronous
     execution framework (e.g. "asyncio") that will be managing the
     *awaitable* object.

Added in version 3.5.

더 보기: **PEP 492** 가 어웨이터블 객체에 대한 더 자세한 정보를 포함하고 있습
      니다.


3.4.2. 코루틴 객체(Coroutine Objects)
-------------------------------------

*Coroutine objects* are *awaitable* objects. A coroutine's execution
can be controlled by calling "__await__()" and iterating over the
result.  When the coroutine has finished executing and returns, the
iterator raises "StopIteration", and the exception's "value" attribute
holds the return value.  If the coroutine raises an exception, it is
propagated by the iterator.  Coroutines should not directly raise
unhandled "StopIteration" exceptions.

코루틴은 다음에 나열하는 메서드들 또한 갖고 있는데, 제너레이터(제너레
이터-이터레이터 메서드 를 보십시오)의 것들과 닮았습니다. 하지만, 제너
레이터와는 달리, 코루틴은 이터레이션을 직접 지원하지는 않습니다.

버전 3.5.2에서 변경: 코루틴을 두 번 await 하면 "RuntimeError" 를 일으
킵니다.

coroutine.send(value)

   Starts or resumes execution of the coroutine.  If *value* is
   "None", this is equivalent to advancing the iterator returned by
   "__await__()".  If *value* is not "None", this method delegates to
   the "send()" method of the iterator that caused the coroutine to
   suspend.  The result (return value, "StopIteration", or other
   exception) is the same as when iterating over the "__await__()"
   return value, described above.

coroutine.throw(value)
coroutine.throw(type[, value[, traceback]])

   Raises the specified exception in the coroutine.  This method
   delegates to the "throw()" method of the iterator that caused the
   coroutine to suspend, if it has such a method.  Otherwise, the
   exception is raised at the suspension point.  The result (return
   value, "StopIteration", or other exception) is the same as when
   iterating over the "__await__()" return value, described above.  If
   the exception is not caught in the coroutine, it propagates back to
   the caller.

   버전 3.12에서 변경: The second signature (type[, value[,
   traceback]]) is deprecated and may be removed in a future version
   of Python.

coroutine.close()

   코루틴이 자신을 정리하고 종료하도록 만듭니다. 만약 코루틴이 일시 중
   지 중이면, 이 메서드는 먼저 코루틴이 일시 중지되도록 한 이터레이터
   의 "close()" 메서드로 위임합니다(그런 메서드를 가지는 경우). 그런
   다음 일시 중지지점에서 "GeneratorExit" 를 발생시키는데, 코루틴이 즉
   시 자신을 정리하도록 만듭니다. 마지막으로 코루틴에 실행을 종료했다
   고 표시하는데, 아직 시작하지조차 않았을 때도 그렇다.

   코루틴 객체가 파괴될 때는 위의 프로세스에 따라 자동으로 닫힙니다
   (closed).


3.4.3. 비동기 이터레이터(Asynchronous Iterators)
------------------------------------------------

*비동기 이터레이터* 는 자신의 "__anext__" 메서드에서 비동기 코드를 호
출할 수 있습니다.

비동기 이터레이터는 "async for" 문에서 사용될 수 있습니다.

The "object" class itself does not provide these methods.

object.__aiter__(self)

   *비동기 이터레이터* 객체를 돌려줘야 합니다.

object.__anext__(self)

   이터레이터의 다음 값을 주는 *어웨이터블* 을 돌려줘야 합니다. 이터레
   이션이 끝나면 "StopAsyncIteration" 에러를 일으켜야 합니다.

비동기 이터러블 객체의 예:

   class Reader:
       async def readline(self):
           ...

       def __aiter__(self):
           return self

       async def __anext__(self):
           val = await self.readline()
           if val == b'':
               raise StopAsyncIteration
           return val

Added in version 3.5.

버전 3.7에서 변경: Prior to Python 3.7, "__aiter__()" could return an
*awaitable* that would resolve to an *asynchronous iterator*.Starting
with Python 3.7, "__aiter__()" must return an asynchronous iterator
object.  Returning anything else will result in a "TypeError" error.


3.4.4. 비동기 컨텍스트 관리자
-----------------------------

*비동기 컨텍스트 관리자(asynchronous context manager)* 는 "__aenter__"
와 "__aexit__" 메서드에서 실행을 일시 중지할 수 있는 *컨텍스트 관리자*
입니다.

비동기 컨텍스트 관리자는 "async with" 문에서 사용될 수 있습니다.

The "object" class itself does not provide these methods.

object.__aenter__(self)

   Semantically similar to "__enter__()", the only difference being
   that it must return an *awaitable*.

object.__aexit__(self, exc_type, exc_value, traceback)

   Semantically similar to "__exit__()", the only difference being
   that it must return an *awaitable*.

비동기 컨텍스트 관리자 클래스의 예:

   class AsyncContextManager:
       async def __aenter__(self):
           await log('entering context')

       async def __aexit__(self, exc_type, exc, tb):
           await log('exiting context')

Added in version 3.5.

-[ 각주 ]-

[1] 어떤 제한된 조건으로, 어떤 경우에 객체의 형을 변경하는 것이 *가능
    합니다*. 하지만 잘못 다뤄지면 아주 괴상한 결과로 이어질 수 있으므
    로 일반적으로 좋은 생각이 아닙니다.

[2] The "__hash__()", "__iter__()", "__reversed__()",
    "__contains__()", "__class_getitem__()" and "__fspath__()" methods
    have special handling for this. Others will still raise a
    "TypeError", but may do so by relying on the behavior that "None"
    is not callable.

[3] "Does not support" here means that the class has no such method,
    or the method returns "NotImplemented".  Do not set the method to
    "None" if you want to force fallback to the right operand's
    reflected method—that will instead have the opposite effect of
    explicitly *blocking* such fallback.

[4] For operands of the same type, it is assumed that if the non-
    reflected method (such as "__add__()") fails then the operation is
    not supported, which is why the reflected method is not called.

[5] If the right operand's type is a subclass of the left operand's
    type, the reflected method having precedence allows subclasses to
    override their ancestors' operations.
