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 (currently implemented as its address). An object’s type is also unchangeable. 1 An object’s type determines the operations that the object supports (e.g., 《does it have a length?》) and also defines the possible values for objects of that type. The type() function returns an object’s type (which is an object itself). The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.

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

CPython implementation detail: CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references. See the documentation of the gc module for information on controlling the collection of cyclic garbage. Other implementations act differently and CPython may change. Do not depend on immediate finalization of objects when they become unreachable (ex: always close files).

구현이 제공하는 추적이나 디버깅 장치의 사용은 그렇지 않으면 수거될 수 있는 객체들을 살아있도록 만들 수 있음에 주의해야 한다. 또한 〈tryexcept〉 문으로 예외를 잡는 것도 객체를 살아있게 만들 수 있다.

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 〈tryfinally〉 statement provides a convenient way to do this.

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

형은 거의 모든 측면에서 객체가 동작하는 방법에 영향을 준다. 객체의 아이엔티디가 갖는 중요성조차도 어떤 면에서는 영향을 받는다: 불변형의 경우, 새 값을 만드는 연산은 실제로는 이미 존재하는 객체 중에서 같은 형과 값을 갖는 것을 돌려줄 수 있다. 반면에 가변 객체에서는 이런 것이 허용되지 않는다. 예를 들어, a = 1; b = 1 후에, ab 는 값 1을 갖는 같은 객체일 수도 있고, 아닐 수도 있다. 하지만 c = []; d = [] 후에, cd 는 두 개의 서로 다르고, 독립적이고, 새로 만들어진 빈 리스트임이 보장된다. (c = d = [] 는 객은 객체를 cd 에 대입한다.)

3.2. 표준형 계층

Below is a list of the types that are built into Python. Extension modules (written in C, Java, or other languages, depending on the implementation) can define additional types. Future versions of Python may add types to the type hierarchy (e.g., rational numbers, efficiently stored arrays of integers, etc.).

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

None

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

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 may 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.) Its truth value is true.

Ellipsis

This type has a single value. There is a single object with this value. This object is accessed through the built-in name Ellipsis. It is used to indicate the presence of the ... syntax in a slice. Its truth value is true.

numbers.Number

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

파이썬은 정수, 실수, 복소수를 구분한다:

numbers.Integral

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

There are three types of integers:

Plain integers

These represent numbers in the range -2147483648 through 2147483647. (The range may be larger on machines with a larger natural word size, but not smaller.) When the result of an operation would fall outside this range, the result is normally returned as a long integer (in some cases, the exception OverflowError is raised instead). For the purpose of shift and mask operations, integers are assumed to have a binary, 2’s complement notation using 32 or more bits, and hiding no bits from the user (i.e., all 4294967296 different bit patterns correspond to different values).

Long integers

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

Booleans

These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of plain integers, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

The rules for integer representation are intended to give the most meaningful interpretation of shift and mask operations involving negative integers and the least surprises when switching between the plain and long integer domains. Any operation, if it yields a result in the plain integer domain, will yield the same result in the long integer domain or when using mixed operands. The switch between domains is transparent to the programmer.

numbers.Real (float)

이것들은 기계 수준의 배정도(double precision) 부동 소수점 수를 나타낸다. 허락되는 값의 범위와 오버플로의 처리에 관해서는 하부 기계의 설계(와 C 나 자바 구현)에 따르는 수밖에 없다. 파이썬은 단정도(single precision) 부동 소수점 수를 지원하지 않는다; 이것들을 사용하는 이유가 되는 프로세서와 메모리의 절감은 파이썬에서 객체를 사용하는데 들어가는 비용과 상쇄되어 미미해진다. 그 때문에 두 가지 종류의 부동 소수점 수로 언어를 복잡하게 만들만한 가치가 없다.

numbers.Complex

이것들은 기계 수준 배정도 부동 소수점 수의 쌍으로 복소수를 나타낸다. 부동 소수점 수와 한계와 문제점을 공유한다. 복소수 z 의 실수부와 허수부는, 읽기 전용 어트리뷰트 z.realz.imag 로 꺼낼 수 있다.

시퀀스들

음이 아닌 정수로 인덱싱(indexing)될 수 있는 유한한 길이의 순서 있는 집합을 나타낸다. 내장함수 len() 은 시퀀스가 가진 항목들의 개수를 돌려준다. 시퀀스의 길이가 n 일 때, 인덱스(index) 집합은 숫자 0, 1, …, n-1을 포함한다. 시퀀스 a 의 항목 ia[i] 로 선택된다.

시퀀스는 슬라이싱도 지원한다: a[i:j]i <= k < j 를 만족하는 모든 항목 k 를 선택한다. 표현식에서 사용될 때, 슬라이스는 같은 형의 시퀀스다. 인덱스 집합은 0에서 시작되도록 다시 번호 매겨진다.

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

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

불변 시퀀스

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

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

문자열(Strings)

The items of a string are characters. There is no separate character type; a character is represented by a string of one item. Characters represent (at least) 8-bit bytes. The built-in functions chr() and ord() convert between characters and nonnegative integers representing the byte values. Bytes with the values 0–127 usually represent the corresponding ASCII values, but the interpretation of values is up to the program. The string data type is also used to represent arrays of bytes, e.g., to hold data read from a file.

(On systems whose native character set is not ASCII, strings may use EBCDIC in their internal representation, provided the functions chr() and ord() implement a mapping between ASCII and EBCDIC, and string comparison preserves the ASCII order. Or perhaps someone can propose a better rule?)

Unicode

The items of a Unicode object are Unicode code units. A Unicode code unit is represented by a Unicode object of one item and can hold either a 16-bit or 32-bit value representing a Unicode ordinal (the maximum value for the ordinal is given in sys.maxunicode, and depends on how Python is configured at compile time). Surrogate pairs may be present in the Unicode object, and will be reported as two separate items. The built-in functions unichr() and ord() convert between code units and nonnegative integers representing the Unicode ordinals as defined in the Unicode Standard 3.0. Conversion from and to other encodings are possible through the Unicode method encode() and the built-in function unicode().

튜플(Tuples)

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

가변 시퀀스

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

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

리스트(Lists)

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

바이트 배열(Byte Arrays)

A bytearray object is a mutable array. They are created by the built-in bytearray() constructor. Aside from being mutable (and hence unhashable), byte arrays otherwise provide the same interface and functionality as immutable bytes objects.

The extension module array provides an additional example of a mutable sequence type.

집합 형들(Set types)

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

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

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

집합(Sets)

이것들은 가변 집합을 나타낸다. 내장 set() 생성자로 만들 수 있고, add() 같은 메서드들을 사용해서 나중에 수정할 수 있다.

불변 집합(Frozen sets)

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

매핑(Mappings)

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

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

딕셔너리(Dictionaries)

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

딕셔너리는 가변이다; {...} 표기법으로 만들 수 있다 (딕셔너리 디스플레이 섹션을 참고하라).

The extension modules dbm, gdbm, and bsddb provide additional examples of mapping types.

콜러블(Callable types)

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

사용자 정의 함수

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

특수 어트리뷰트들(Special attributes):

어트리뷰트

의미

__doc__ func_doc

The function’s documentation string, or None if unavailable.

쓰기 가능

__name__ func_name

함수의 이름

쓰기 가능

__module__

함수가 정의된 모듈의 이름 또는 (없는 경우) None

쓰기 가능

__defaults__ func_defaults

A tuple containing default argument values for those arguments that have defaults, or None if no arguments have a default value.

쓰기 가능

__code__ func_code

컴파일된 함수의 바디(body) 를 나타내는 코드 객체

쓰기 가능

__globals__ func_globals

함수의 전역 변수들을 가진 딕셔너리에 대한 참조 — 함수가 정의된 모듈의 전역 이름 공간(namespace)

읽기 전용

__dict__ func_dict

임의의 함수 어트리뷰트를 지원하는 이름 공간.

쓰기 가능

__closure__ func_closure

None 또는 함수의 자유 변수(free variable)들에 대한 연결을 가진 셀(cell)들의 튜플.

읽기 전용

《쓰기 가능》 하다고 표시된 대부분의 어트리뷰트들은 값이 대입될 때 형을 검사한다.

버전 2.4에서 변경: func_name is now writable.

버전 2.6에서 변경: The double-underscore attributes __closure__, __code__, __defaults__, and __globals__ were introduced as aliases for the corresponding func_* attributes for forwards compatibility with Python 3.

함수 객체는 임의의 어트리뷰트를 읽고 쓸 수 있도록 지원하는데, 예를 들어 함수에 메타데이터(metadata)를 붙이는데 사용될 수 있다. 어트리뷰트를 읽거나 쓸 때는 일반적인 점 표현법(dot-notation)이 사용된다. 현재 구현은 오직 사용자 정의 함수만 함수 어트리뷰트를 지원함에 주의해야 한다. 내장 함수의 함수 어트리뷰트는 미래에 지원될 수 있다.

함수 정의에 관한 추가적인 정보를 코드 객체로부터 얻을 수 있다. 아래에 나오는 내부 형의 기술을 참고하라.

User-defined methods

A user-defined method object combines a class, a class instance (or None) and any callable object (normally a user-defined function).

Special read-only attributes: im_self is the class instance object, im_func is the function object; im_class is the class of im_self for bound methods or the class that asked for the method for unbound methods; __doc__ is the method’s documentation (same as im_func.__doc__); __name__ is the method name (same as im_func.__name__); __module__ is the name of the module the method was defined in, or None if unavailable.

버전 2.2에서 변경: im_self used to refer to the class that defined the method.

버전 2.6에서 변경: For Python 3 forward-compatibility, im_func is also available as __func__, and im_self as __self__.

메서드는 기반 함수의 모든 함수 어트리뷰트들을 읽을 수 있도록 지원한다(하지만 쓰기는 지원하지 않는다).

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, an unbound user-defined method object, or a class method object. When the attribute is a user-defined method object, a new method object is only created if the class from which it is being retrieved is the same as, or a derived class of, the class stored in the original method object; otherwise, the original method object is used as it is.

When a user-defined method object is created by retrieving a user-defined function object from a class, its im_self attribute is None and the method object is said to be unbound. When one is created by retrieving a user-defined function object from a class via one of its instances, its im_self attribute is the instance, and the method object is said to be bound. In either case, the new method’s im_class attribute is the class from which the retrieval takes place, and its im_func attribute is the original function object.

When a user-defined method object is created by retrieving another method object from a class or instance, the behaviour is the same as for a function object, except that the im_func attribute of the new instance is not the original method object but its im_func attribute.

When a user-defined method object is created by retrieving a class method object from a class or instance, its im_self attribute is the class itself, and its im_func attribute is the function object underlying the class method.

When an unbound user-defined method object is called, the underlying function (im_func) is called, with the restriction that the first argument must be an instance of the proper class (im_class) or of a derived class thereof.

When a bound user-defined method object is called, the underlying function (im_func) is called, inserting the class instance (im_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 a user-defined method object is derived from a class method object, the 《class instance》 stored in im_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.

Note that the transformation from function object to (unbound or bound) method object happens each time the attribute is retrieved from the class or instance. In some cases, a fruitful optimization is to assign the attribute to a local variable and call that local variable. Also notice that this transformation only happens for user-defined functions; other callable objects (and all non-callable objects) are retrieved without transformation. It is also 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.

제너레이터 함수(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 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.

내장 함수(Built-in functions)

내장 함수 객체는 C 함수를 둘러싸고 있다(wrapper). 내장 함수의 예로는 len()math.sin() (math 는 표준 내장 모듈이다) 가 있다. 인자의 개수와 형은 C 함수에 의해 결정된다. 특수 읽기 전용 어트리뷰트들: __doc__ 은 함수의 설명 문자열 또는 없는 경우 None 이다; __name__ 은 함수의 이름이다; __self__None 으로 설정된다 (하지만 다음 항목을 보라); __module__ 은 함수가 정의된 모듈의 이름이거나 없는 경우 None 이다.

내장 메서드(Built-in methods)

이것은 사실 내장 함수의 다른 모습이다. 이번에는 묵시적인 추가의 인자로 C 함수에 전달되는 객체를 갖고 있다. 내장 메서드의 예로는 alist.append() 가 있는데, alist 는 리스트 객체다. 이 경우에, 특수 읽기 전용 어트리뷰트 __self__alist 로 표현된 객체로 설정된다.

Class Types

Class types, or 《new-style 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.

Classic Classes

Class objects are described below. When a class object is called, a new class instance (also described below) is created and returned. This implies a call to the class’s __init__() method if it has one. Any arguments are passed on to the __init__() method. If there is no __init__() method, the class must be called without arguments.

클래스 인스턴스(Class instances)

Class instances are described below. Class instances are callable only when the class has a __call__() method; x(arguments) is a shorthand for x.__call__(arguments).

모듈(Modules)

Modules are imported by the import statement (see section 임포트(import) 문). A module object has a namespace implemented by a dictionary object (this is the dictionary referenced by the func_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 = 1m.__dict__["x"] = 1 과 같다.

특수 읽기 전용 어트리뷰트들: __dict__ 는 딕셔너리로 표현되는 모듈의 이름 공간이다.

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

Predefined (writable) attributes: __name__ is the module’s name; __doc__ is the module’s documentation string, or None if unavailable; __file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

클래스(Classes)

Both class types (new-style classes) and class objects (old-style/classic classes) 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 for new-style classes in particular 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. For old-style classes, the search is depth-first, left-to-right in the order of occurrence in the base class list. New-style classes use the more complex 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 new-style classes can be found in the documentation accompanying the 2.3 release at https://www.python.org/download/releases/2.3/mro/.

When a class attribute reference (for class C, say) would yield a user-defined function object or an unbound user-defined method object whose associated class is either C or one of its base classes, it is transformed into an unbound user-defined method object whose im_class attribute is C. When it would yield a class method object, it is transformed into a bound user-defined method object whose im_self attribute is C. When it would yield a static method 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__ (note that only new-style classes support descriptors).

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

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

Special attributes: __name__ is the class name; __module__ is the module name in which the class was defined; __dict__ is the dictionary containing the class’s namespace; __bases__ is a tuple (possibly empty or a singleton) containing the base classes, in the order of their occurrence in the base class list; __doc__ is the class’s documentation string, or None if undefined.

클래스 인스턴스(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 or an unbound user-defined method object whose associated class is the class (call it C) of the instance for which the attribute reference was initiated or one of its bases, it is transformed into a bound user-defined method object whose im_class attribute is C and whose im_self attribute is the instance. Static method and class method objects are also transformed, as if they had been retrieved from class C; 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.

어트리뷰트 대입과 삭제는 인스턴스의 딕셔너리를 갱신할 뿐, 결코 클래스의 딕셔너리를 건드리지 않는다. 만약 클래스가 __setattr__() 이나 __delattr__() 메서드를 가지면, 인스턴스의 딕셔너리를 갱신하는 대신에 그 메서드들을 호출한다.

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

특수 어트리뷰트들: __dict__ 는 어트리뷰트 딕셔너리다; __class__ 는 인스턴스의 클래스다.

Files

A file object represents an open file. File objects are created by the open() built-in function, and also by os.popen(), os.fdopen(), and the makefile() method of socket objects (and perhaps by other functions or methods provided by extension modules). The objects sys.stdin, sys.stdout and sys.stderr are initialized to file objects corresponding to the interpreter’s standard input, output and error streams. See File Objects for complete documentation of file objects.

내부 형(Internal types)

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

코드 객체(Code objects)

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

특수 읽기 전용 어트리뷰트들: co_name 은 함수의 이름이다; co_argcount 는 위치 인자들 (기본값이 있는 인자들도 포함된다)의 개수다; co_nlocals 는 함수가 사용하는 지역 변수들 (인자들을 포함한다)의 개수다; co_varnames 는 지역 변수들의 이름을 담고 있는 튜플이다(인자들의 이름이 먼저 나온다); co_cellvars 는 중첩된 함수들이 참조하는 지역 변수들의 이름을 담고 있는 튜플이다; co_freevars 는 자유 변수(free variables)들의 이름을 담고 있는 튜플이다; co_code 는 바이트 코드 명령 시퀀스를 나타내는 문자열이다; co_consts 는 바이트 코드가 사용하는 리터럴을 포함하는 튜플이다; co_names 는 바이트 코드가 사용하는 이름들을 담고 있는 튜플이다; co_filename 은 컴파일된 코드를 제공한 파일의 이름이다; co_firstlineno 는 함수의 첫 번째 줄 번호다; co_lnotab 은 바이트 코드에서의 위치를 줄 번호로 매핑하는 법을 문자열로 인코딩한 값이다 (자세한 내용은 인터프리터의 소스 코드를 참고하라); co_stacksize 는 필요한 스택의 크기다 (지역 변수를 포함한다); co_flags 는 인터프리터의 여러 플래그(flag)들을 정수로 인코딩한 값이다.

다음과 같은 값들이 co_flags 를 위해 정의되어 있다: 함수가 가변 개수의 위치 인자를 받아들이기 위해 사용되는 *arguments 문법을 사용하면 비트 0x04 가 1이 된다; 임의의 키워드 인자를 받아들이기 위해 사용하는 **keywords 문법을 사용하면 비트 0x08 이 1이 된다; 비트 0x20 은 함수가 제너레이터일 때 설정된다.

퓨처 기능 선언 (from __future__ import division) 또한 코드 객체가 특정 기능이 활성화된 상태에서 컴파일되었는지를 나타내기 위해 co_flags 의 비트들을 사용한다: 함수가 퓨처 division이 활성화된 상태에서 컴파일되었으면 비트 0x2000 이 설정된다; 비트 0x100x1000 는 예전 버전의 파이썬에서 사용되었다.

co_flags 의 다른 비트들은 내부 사용을 위해 예약되어 있다.

만약 코드 객체가 함수를 나타낸다면, co_consts 의 첫 번째 항목은 설명 문자열이거나 정의되지 않으면 None 이다.

프레임 객체(Frame objects)

프레임 객체는 실행 프레임(execution frame)을 나타낸다. 트레이스백 객체에 등장할 수 있다 (아래를 보라).

Special read-only attributes: f_back is to the previous stack frame (towards the caller), or None if this is the bottom stack frame; f_code is the code object being executed in this frame; f_locals is the dictionary used to look up local variables; f_globals is used for global variables; f_builtins is used for built-in (intrinsic) names; f_restricted is a flag indicating whether the function is executing in restricted execution mode; f_lasti gives the precise instruction (this is an index into the bytecode string of the code object).

Special writable attributes: f_trace, if not None, is a function called at the start of each source code line (this is used by the debugger); f_exc_type, f_exc_value, f_exc_traceback represent the last exception raised in the parent frame provided another exception was ever raised in the current frame (in all other cases they are None); f_lineno is 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 f_lineno.

트레이스백 객체(Traceback objects)

Traceback objects represent a stack trace of an exception. A traceback object is created when an exception occurs. 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 sys.exc_traceback, and also as the third item of the tuple returned by sys.exc_info(). The latter is the preferred interface, since it works correctly when the program is using multiple threads. 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.

특수 읽기 전용 어트리뷰트들: tb_next 는 스택 트레이스의 다음 단계 (예외가 발생한 프레임 방향으로)이거나 다음 단계가 없으면 None 이다. tb_frame 은 현 단계에서의 실행 프레임이다; tb_lineno 는 예외가 발생한 줄의 번호를 준다; tb_lasti 정확한 바이트 코드 명령을 가리킨다. 만약 예외가 except 절이나 finally 절이 없는 try 문에서 발생하면, 줄 번호와 트레이스백의 마지막 명령(last instruction)은 프레임 객체의 줄 번호와 다를 수 있다.

슬라이스 객체(Slice objects)

Slice objects are used to represent slices when extended slice syntax is used. This is a slice using two colons, or multiple slices or ellipses separated by commas, e.g., a[i:j:step], a[i:j, k:l], or a[..., i:j]. They are also created by the built-in slice() function.

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

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

slice.indices(self, length)

This method takes a single integer argument length and computes information about the extended slice that the slice object would describe if applied to a sequence of length items. It returns a tuple of three integers; respectively these are the start and stop indices and the step or stride length of the slice. Missing or out-of-bounds indices are handled in a manner consistent with regular slices.

버전 2.3에 추가.

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

스태틱 메서드 객체는 위에서 설명한 함수 객체를 메서드 객체로 변환하는 과정을 방지하는 방법을 제공한다. 스태틱 메서드 객체는 다른 임의의 객체, 보통 사용자 정의 메서드를 둘러싼다. 스태틱 메서드가 클래스나 클래스 인스턴스로부터 읽힐 때 객체가 실제로 돌려주는 것은 둘러싸여 있던 객체인데, 다른 어떤 변환도 적용되지 않은 상태다. 둘러싸는 객체는 그렇더라도, 스태틱 메서드 객체 자체는 콜러블이 아니다. 스태틱 메서드 객체는 내장 staticmethod() 생성자로 만든다.

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

스태틱 메서드 객체처럼, 클래스 메서드 객체 역시 다른 객체를 둘러싸는데, 클래스와 클래스 인스턴스로부터 그 객체를 꺼내는 방식에 변화를 준다. 그런 조회에서 클래스 메서드 객체가 동작하는 방식에 대해서는 위 《사용자 정의 메서드(User-defined methods)》 에서 설명했다. 클래스 메서드 객체는 내장 classmethod() 생성자로 만든다.

3.3. New-style and classic classes

Classes and instances come in two flavors: old-style (or classic) and new-style.

Up to Python 2.1 the concept of class was unrelated to the concept of type, and old-style classes were the only flavor available. For an old-style class, the statement x.__class__ provides the class of x, but type(x) is always <type 'instance'>. This reflects the fact that all old-style instances, independent of their class, are implemented with a single built-in type, called instance.

New-style classes were introduced in Python 2.2 to unify the concepts of class and type. A new-style class is simply a user-defined type, no more, no less. If x is an instance of a new-style class, then type(x) is typically the same as x.__class__ (although this is not guaranteed – a new-style class instance is permitted to override the value returned for x.__class__).

The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model. It also has a number of practical benefits, like the ability to subclass most built-in types, or the introduction of 《descriptors》, which enable computed properties.

For compatibility reasons, classes are still old-style by default. New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the 《top-level type》 object if no other parent is needed. The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type() returns. Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are 《fixes》 that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.

While this manual aims to provide comprehensive coverage of Python’s class mechanics, it may still be lacking in some areas when it comes to its coverage of new-style classes. Please see https://www.python.org/doc/newstyle/ for sources of additional information.

Old-style classes are removed in Python 3, leaving only new-style classes.

3.4. 특수 메서드 이름들

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 x.__getitem__(i) for old-style classes and type(x).__getitem__(x, i) for new-style classes. Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined (typically AttributeError or TypeError).

내장형을 흉내 내는 클래스를 구현할 때, 모방은 모형화하는 객체에 말이 되는 수준까지만 구현하는 것이 중요하다. 예를 들어, 어떤 시퀀스는 개별 항목들을 꺼내는 것만으로도 잘 동작할 수 있다. 하지만 슬라이스를 꺼내는 것은 말이 안 될 수 있다. (이런 한가지 예는 W3C의 Document Object Model의 NodeList 인터페이스다.)

3.4.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(currentclass, cls).__new__(cls[, ...]) with appropriate arguments and then modifying the newly-created instance as necessary before returning it.

만약 __new__()cls 의 인스턴스를 돌려준다면, 새 인스턴스의 __init__() 메서드가 __init__(self[, ...]) 처럼 호출되는데, self 는 새 인스턴스이고, 나머지 인자들은 __new__() 로 전달된 것들과 같다.

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

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

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

Called after the instance has been created (by __new__()), but before it is returned to the caller. The arguments are those passed to the class constructor expression. If a base class has an __init__() method, the derived class’s __init__() method, if any, must explicitly call it to ensure proper initialization of the base class part of the instance; for example: BaseClass.__init__(self, [args...]).

Because __new__() and __init__() work together in constructing objects (__new__() to create it, and __init__() to customise it), no non-None value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime.

object.__del__(self)

Called when the instance is about to be destroyed. This is also called a destructor. If a base class has a __del__() method, the derived class’s __del__() method, if any, must explicitly call it to ensure proper deletion of the base class part of the instance. Note that it is possible (though not recommended!) for the __del__() method to postpone destruction of the instance by creating a new reference to it. It may then be called at a later time when this new reference is deleted. It is not guaranteed that __del__() methods are called for objects that still exist when the interpreter exits.

참고

del x doesn’t directly call x.__del__() — the former decrements the reference count for x by one, and the latter is only called when x’s reference count reaches zero. Some common situations that may prevent the reference count of an object from going to zero include: circular references between objects (e.g., a doubly-linked list or a tree data structure with parent and child pointers); a reference to the object on the stack frame of a function that caught an exception (the traceback stored in sys.exc_traceback keeps the stack frame alive); or a reference to the object on the stack frame that raised an unhandled exception in interactive mode (the traceback stored in sys.last_traceback keeps the stack frame alive). The first situation can only be remedied by explicitly breaking the cycles; the latter two situations can be resolved by storing None in sys.exc_traceback or sys.last_traceback. Circular references which are garbage are detected when the option cycle detector is enabled (it’s on by default), but can only be cleaned up if there are no Python-level __del__() methods involved. Refer to the documentation for the gc module for more information about how __del__() methods are handled by the cycle detector, particularly the description of the garbage value.

경고

Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down). For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants. Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the __del__() method is called.

See also the -R command-line option.

object.__repr__(self)

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the 《official》 string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form <...some useful description...> should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an 《informal》 string representation of instances of that class is required.

이것은 디버깅에 사용되기 때문에, 표현이 풍부한 정보를 담고 모호하지 않게 하는 것이 중요하다.

object.__str__(self)

Called by the str() built-in function and by the print statement to compute the 《informal》 string representation of an object. This differs from __repr__() in that it does not have to be a valid Python expression: a more convenient or concise representation may be used instead. The return value must be a string object.

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

버전 2.1에 추가.

These are the so-called 《rich comparison》 methods, and are called for comparison operators in preference to __cmp__() below. The correspondence between operator symbols and method names is as follows: x<y calls x.__lt__(y), x<=y calls x.__le__(y), x==y calls x.__eq__(y), x!=y and x<>y call x.__ne__(y), x>y calls x.__gt__(y), and x>=y calls x.__ge__(y).

풍부한 비교 메서드는 주어진 한 쌍의 인자에게 해당 연산을 구현하지 않는 경우 단일자(singleton) NotImplemented 를 돌려줄 수 있다. 관례상, 성공적인 비교면 FalseTrue 를 돌려준다. 하지만, 이 메서드는 어떤 형의 값이건 돌려줄 수 있다, 그래서 비교 연산자가 논리 문맥(Boolean context) (예를 들어 if 문의 조건)에서 사용되면, 파이썬은 결과의 참 거짓을 파악하기 위해 값에 대해 bool() 을 호출한다.

There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false. Accordingly, when defining __eq__(), one should also define __ne__() so that the operators will behave as expected. See the paragraph on __hash__() for some important notes on creating hashable objects which support custom comparison operations and are usable as dictionary keys.

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.

Arguments to rich comparison methods are never coerced.

To automatically generate ordering operations from a single root operation, see functools.total_ordering().

object.__cmp__(self, other)

Called by comparison operations if rich comparison (see above) is not defined. Should return a negative integer if self < other, zero if self == other, a positive integer if self > other. If no __cmp__(), __eq__() or __ne__() operation is defined, class instances are compared by object identity (《address》). See also the description of __hash__() for some important notes on creating hashable objects which support custom comparison operations and are usable as dictionary keys. (Note: the restriction that exceptions are not propagated by __cmp__() has been removed since Python 1.5.)

object.__rcmp__(self, other)

버전 2.1에서 변경: No longer supported.

object.__hash__(self)

Called by built-in function hash() and for operations on members of hashed collections including set, frozenset, and dict. __hash__() 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))

If a class does not define a __cmp__() or __eq__() method it should not define a __hash__() operation either; if it defines __cmp__() or __eq__() but not __hash__(), its instances will not be usable in hashed collections. If a class defines mutable objects and implements a __cmp__() or __eq__() method, it should not implement __hash__(), since hashable collection implementations require that an object’s hash value is immutable (if the object’s hash value changes, it will be in the wrong hash bucket).

User-defined classes have __cmp__() and __hash__() methods by default; with them, all objects compare unequal (except with themselves) and x.__hash__() returns a result derived from id(x).

Classes which inherit a __hash__() method from a parent class but change the meaning of __cmp__() or __eq__() such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting __hash__ = None in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checking isinstance(obj, collections.Hashable) (unlike classes which define their own __hash__() to explicitly raise TypeError).

버전 2.5에서 변경: __hash__() may now also return a long integer object; the 32-bit integer is then derived from the hash of that object.

버전 2.6에서 변경: __hash__ may now be set to None to explicitly flag instances of a class as unhashable.

object.__nonzero__(self)

Called to implement truth value testing and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. 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 __nonzero__(), all its instances are considered true.

object.__unicode__(self)

Called to implement unicode() built-in; should return a Unicode object. When this method is not defined, string conversion is attempted, and the result of string conversion is converted to Unicode using the system default encoding.

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

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

object.__getattr__(self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.

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 fake 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 in new-style classes.

object.__setattr__(self, name, value)

Called when an attribute assignment is attempted. This is called instead of the normal mechanism (i.e. store the value in the instance dictionary). name is the attribute name, value is the value to be assigned to it.

If __setattr__() wants to assign to an instance attribute, it should not simply execute self.name = value — this would cause a recursive call to itself. Instead, it should insert the value in the dictionary of instance attributes, e.g., self.__dict__[name] = value. For new-style classes, rather than accessing the instance dictionary, it should call the base class method with the same name, for example, object.__setattr__(self, name, value).

object.__delattr__(self, name)

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

3.4.2.1. More attribute access for new-style classes

The following methods only apply to new-style classes.

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 Special method lookup for new-style classes.

3.4.2.2. 디스크립터 구현하기

다음에 오는 메서드들은 메서드를 가진 클래스(소위 디스크립터(descriptor) 클래스)의 인스턴스가 소유자(owner) 클래스에 등장할 때만 적용된다(디스크립터는 소유자 클래스의 딕셔너리나 그 부모 클래스 중 하나의 딕셔너리에 있어야 한다). 아래의 예에서, 《어트리뷰트》 는 이름이 소유자 클래스의 __dict__ 의 키로 사용되고 있는 어트리뷰트를 가리킨다.

object.__get__(self, instance, owner)

소유자 클래스(클래스 어트리뷰트 액세스) 나 그 클래스의 인스턴스(인스턴스 어트리뷰트 액세스)의 어트리뷰트를 취하려고 할 때 호출된다. owner 는 항상 소유자 클래스다. 반면에 instance 는 어트리뷰트 참조가 일어나고 있는 인스턴스이거나, 어트리뷰트가 owner 를 통해 액세스 되는 경우 None 이다. 이 메서드는 (계산된) 어트리뷰트 값을 돌려주거나 AttributeError 예외를 일으켜야 한다.

object.__set__(self, instance, value)

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

object.__delete__(self, instance)

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

3.4.2.3. 디스크립터 호출하기

일반적으로, 디스크립터는 《결합한 동작(binding behavior)》을 가진 객체 어트리뷰트다. 어트리뷰트 액세스가 디스크립터 프로토콜(descriptor protocol)의 메서드들에 의해 재정의된다: __get__(), __set__(), __delete__(). 이 메서드들 중 하나라도 정의되어 있으면, 디스크립터라고 부른다.

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

However, if the looked-up value is an object defining one of the descriptor methods, then Python may override the default behavior and invoke the descriptor method instead. Where this occurs in the precedence chain depends on which descriptor methods were defined and how they were called. Note that descriptors are only invoked for new style objects or classes (ones that subclass object() or type()).

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

직접 호출

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

인스턴스 결합

If binding to a new-style object instance, a.x is transformed into the call: type(a).__dict__['x'].__get__(a, type(a)).

클래스 결합

If binding to a new-style class, A.x is transformed into the call: A.__dict__['x'].__get__(None, A).

Super 결합

super 의 인스턴스에 결합하면, 결합 super(B, obj).m()obj.__class__.__mro__ 를 검색해서 B 바로 다음에 나오는 베이스 클래스 A 를 찾은 후에 이렇게 디스크립터를 호출한다: A.__dict__['m'].__get__(obj, obj.__class__).

인스턴스 결합의 경우, 디스크립터 호출의 우선순위는 어떤 디스크립터 메서드가 정의되어있는지에 따라 다르다. 디스크립터는 __get__(), __set__(), __delete__() 를 어떤 조합으로도 정의할 수 있다. 만약 __get__() 를 정의하지 않는다면, 어트리뷰트 액세스는, 객체의 인스턴스 딕셔너리에 값이 있지 않은 이상 디스크립터 객체 자신을 돌려준다. 만약 디스크립터가 __set__() 이나 __delete__() 중 어느 하나나 둘 다 정의하면, 데이터 디스크립터(data descriptor)다. 둘 다 정의하지 않는다면 비데이터 디스크립터다(non-data descriptor). 보통, 데이터 디스크립터가 __get__()__set__() 을 모두 정의하는 반면, 비데이터 디스크립터는 __get__() 메서드만 정의한다. __set__()__get__() 이 있는 데이터 디스크립터는 이스턴스 딕셔너리에 있는 값에 우선한다. 반면에 비데이터 디스크립터는 인스턴스보다 우선순위가 낮다.

파이썬 메서드 (staticmethod()classmethod() 를 포함해서) 는 비데이터 디스크립터로 구현된다. 이 때문에, 인스턴스는 메서드를 새로 정의하거나 덮어쓸 수 있다. 이것은 개별 인스턴스가 같은 클래스의 다른 인스턴스들과는 다른 동작을 얻을 수 있도록 만든다.

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

3.4.2.4. __slots__

By default, instances of both old and new-style classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances.

The default can be overridden by defining __slots__ in a new-style class definition. The __slots__ declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because __dict__ is not created for each instance.

__slots__

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

버전 2.2에 추가.

__slots__ 사용에 관한 노트

  • When inheriting from a class without __slots__, the __dict__ attribute of that class will always be accessible, so a __slots__ definition in the subclass is meaningless.

  • __dict__ 변수가 없으므로 인스턴스는 __slots__ 정의에 나열되지 않은 새 변수를 대입할 수 없다. 나열되지 않은 변수명으로 대입하려고 하면 AttributeError 를 일으킨다. 만약 동적으로 새 변수를 대입하는 것이 필요하다면, __slots__ 선언의 문자열 시퀀스에 '__dict__' 를 추가한다.

    버전 2.3에서 변경: Previously, adding '__dict__' to the __slots__ declaration would not enable the assignment of new attributes not specifically listed in the sequence of instance variable names.

  • 인스턴스마다 __weakref__ 변수가 없으므로, __slots__ 를 정의하는 클래스는 인스턴스에 대한 약한 참조(weak reference)를 지원하지 않는다. 만약 약한 참조 지원이 필요하다면, __slots__ 선언의 문자열 시퀀스에 '__weakref__' 를 추가한다.

    버전 2.3에서 변경: Previously, adding '__weakref__' to the __slots__ declaration would not enable support for weak references.

  • __slots__ 는 각 변수 이름마다 디스크립터를 만드는 방식으로 클래스 수준에서 구현된다(디스크립터 구현하기). 결과적으로, 클래스 어트리뷰트는 __slots__ 로 정의된 인스턴스 변수들을 위한 기본값을 제공할 목적으로 사용될 수 없다. 클래스 어트리뷰트는 디스크립터 대입을 무효로 한다.

  • The action of a __slots__ declaration is limited to the class where it is defined. As a result, subclasses will have a __dict__ unless they also define __slots__ (which must only contain names of any additional slots).

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

  • Nonempty __slots__ does not work for classes derived from 《variable-length》 built-in types such as long, str and tuple.

  • __slots__ 에는 문자열 이외의 이터러블을 대입할 수 있다. 매핑도 역시 사용할 수 있다. 하지만, 미래에, 각 키에 대응하는 값들의 의미가 부여될 수 있다.

  • 두 클래스가 같은 __slots__ 을 갖는 경우만 __class__ 대입이 동작한다.

    버전 2.6에서 변경: Previously, __class__ assignment raised an error if either new or old class had __slots__.

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

By default, new-style classes are constructed using type(). A class definition is read into a separate namespace and the value of class name is bound to the result of type(name, bases, dict).

When the class definition is read, if __metaclass__ is defined then the callable assigned to it will be called instead of type(). This allows classes or functions to be written which monitor or alter the class creation process:

  • Modifying the class dictionary prior to the class being created.

  • Returning an instance of another class – essentially performing the role of a factory function.

These steps will have to be performed in the metaclass’s __new__() method – type.__new__() can then be called from this method to create a class with different properties. This example adds a new element to the class dictionary before creating the class:

class metacls(type):
    def __new__(mcs, name, bases, dict):
        dict['foo'] = 'metacls was here'
        return type.__new__(mcs, name, bases, dict)

You can of course also override other class methods (or add new methods); for example defining a custom __call__() method in the metaclass allows custom behavior when the class is called, e.g. not always creating a new instance.

__metaclass__

This variable can be any callable accepting arguments for name, bases, and dict. Upon class creation, the callable is used instead of the built-in type().

버전 2.2에 추가.

The appropriate metaclass is determined by the following precedence rules:

  • If dict['__metaclass__'] exists, it is used.

  • Otherwise, if there is at least one base class, its metaclass is used (this looks for a __class__ attribute first and if not found, uses its type).

  • Otherwise, if a global variable named __metaclass__ exists, it is used.

  • Otherwise, the old-style, classic metaclass (types.ClassType) is used.

The potential uses for metaclasses are boundless. Some ideas that have been explored including logging, interface checking, automatic delegation, automatic property creation, proxies, frameworks, and automatic resource locking/synchronization.

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

버전 2.6에 추가.

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

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

class.__instancecheck__(self, instance)

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

class.__subclasscheck__(self, subclass)

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

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

더 보기

PEP 3119 - 추상 베이스 클래스의 도입

__instancecheck__()__subclasscheck__() 를 통해 isinstance()issubclass() 의 동작을 커스터마이징하는 데 필요한 규약을 포함하는데, 이 기능의 동기는 언어에 추상 베이스 클래스 (abc 모듈을 보라)를 추가하고자 하는 데 있다.

3.4.5. 콜러블 객체 흉내 내기

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

인스턴스가 함수처럼 《호출될》 때 호출된다; 이 메서드가 정의되면, x(arg1, arg2, ...)x.__call__(arg1, arg2, ...) 의 줄인 표현이다.

3.4.6. 컨테이너형 흉내 내기

The following methods can be defined to implement container objects. 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. (For backwards compatibility, the method __getslice__() (see below) can also be defined to handle simple, but not extended slices.) It is also recommended that mappings provide the methods keys(), values(), items(), has_key(), get(), clear(), setdefault(), iterkeys(), itervalues(), iteritems(), pop(), popitem(), copy(), and update() behaving similar to those for Python’s standard dictionary objects. The UserDict module provides a DictMixin class to help create those methods from a base set of __getitem__(), __setitem__(), __delitem__(), and keys(). Mutable sequences should provide methods append(), count(), index(), extend(), insert(), pop(), remove(), reverse() and sort(), 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 __coerce__() or 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 be equivalent of has_key(); 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 be the same as iterkeys(); 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 __nonzero__() method and whose __len__() method returns zero is considered to be false in a Boolean context.

CPython implementation detail: 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 __nonzero__() method.

object.__getitem__(self, key)

self[key] 의 값을 구하기 위해 호출된다. 시퀀스형의 경우, 정수와 슬라이스 객체만 키로 허용된다. 음수 인덱스(만약 클래스가 시퀀스 형을 흉내 내길 원한다면)의 특별한 해석은 __getitem__() 메서드에 달려있음에 주의해야 한다. 만약 key 가 적절하지 않은 형인 경우, TypeError 가 발생할 수 있다; 만약 시퀀스의 인덱스 범위를 벗어나면(음수에 대한 특별한 해석 후에), IndexError 를 일으켜야 한다. 매핑 형의 경우, key 가 (컨테이너에) 없으면, KeyError 를 일으켜야 한다.

참고

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

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, and should also be made available as the method iterkeys().

이터레이터 객체 역시 이 메서드를 구현할 필요가 있다; 자기 자신을 돌려줘야 한다. 이터레이터 객체에 대한 추가의 정보는 이터레이터 형 에 있다.

object.__reversed__(self)

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

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

버전 2.6에 추가.

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

object.__contains__(self, item)

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

__contains__() 를 정의하지 않는 객체의 경우, 멤버십 검사는 먼저 __iter__() 를 통한 이터레이션을 시도한 후, __getitem__() 을 통한 낡은 시퀀스 이터레이션 프로토콜을 시도한다. membership-test-details 섹션을 참고하라.

3.4.7. Additional methods for emulation of sequence types

The following optional methods can be defined to further emulate sequence objects. Immutable sequences methods should at most only define __getslice__(); mutable sequences might define all three methods.

object.__getslice__(self, i, j)

버전 2.0부터 폐지: Support slice objects as parameters to the __getitem__() method. (However, built-in types in CPython currently still implement __getslice__(). Therefore, you have to override it in derived classes when implementing slicing.)

Called to implement evaluation of self[i:j]. The returned object should be of the same type as self. Note that missing i or j in the slice expression are replaced by zero or sys.maxsize, respectively. If negative indexes are used in the slice, the length of the sequence is added to that index. If the instance does not implement the __len__() method, an AttributeError is raised. No guarantee is made that indexes adjusted this way are not still negative. Indexes which are greater than the length of the sequence are not modified. If no __getslice__() is found, a slice object is created instead, and passed to __getitem__() instead.

object.__setslice__(self, i, j, sequence)

Called to implement assignment to self[i:j]. Same notes for i and j as for __getslice__().

This method is deprecated. If no __setslice__() is found, or for extended slicing of the form self[i:j:k], a slice object is created, and passed to __setitem__(), instead of __setslice__() being called.

object.__delslice__(self, i, j)

Called to implement deletion of self[i:j]. Same notes for i and j as for __getslice__(). This method is deprecated. If no __delslice__() is found, or for extended slicing of the form self[i:j:k], a slice object is created, and passed to __delitem__(), instead of __delslice__() being called.

Notice that these methods are only invoked when a single slice with a single colon is used, and the slice method is available. For slice operations involving extended slice notation, or in absence of the slice methods, __getitem__(), __setitem__() or __delitem__() is called with a slice object as argument.

The following example demonstrate how to make your program or module compatible with earlier versions of Python (assuming that methods __getitem__(), __setitem__() and __delitem__() support slice objects as arguments):

class MyClass:
    ...
    def __getitem__(self, index):
        ...
    def __setitem__(self, index, value):
        ...
    def __delitem__(self, index):
        ...

    if sys.version_info < (2, 0):
        # They won't be defined if version is at least 2.0 final

        def __getslice__(self, i, j):
            return self[max(0, i):max(0, j):]
        def __setslice__(self, i, j, seq):
            self[max(0, i):max(0, j):] = seq
        def __delslice__(self, i, j):
            del self[max(0, i):max(0, j):]
    ...

Note the calls to max(); these are necessary because of the handling of negative indices before the __*slice__() methods are called. When negative indexes are used, the __*item__() methods receive them as provided, but the __*slice__() methods get a 《cooked》 form of the index values. For each negative index value, the length of the sequence is added to the index before calling the method (which may still result in a negative index); this is the customary handling of negative indexes by the built-in sequence types, and the __*item__() methods are expected to do this as well. However, since they should already be doing that, negative indexes cannot be passed in; they must be constrained to the bounds of the sequence before being passed to the __*item__() methods. Calling max(0, i) conveniently returns the proper value.

3.4.8. 숫자 형 흉내 내기

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

object.__add__(self, other)
object.__sub__(self, other)
object.__mul__(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, x.__add__(y) is called. The __divmod__() method should be the equivalent to using __floordiv__() and __mod__(); it should not be related to __truediv__() (described below). Note that __pow__() should be defined to accept an optional third argument if the ternary version of the built-in pow() function is to be supported.

만약 이 메서드들 중 하나가 제공된 인자에 대해 연산을 지원하지 않으면, NotImplemented 를 돌려줘야 한다.

object.__div__(self, other)
object.__truediv__(self, other)

The division operator (/) is implemented by these methods. The __truediv__() method is used when __future__.division is in effect, otherwise __div__() is used. If only one of these two methods is defined, the object will not support division in the alternate context; TypeError will be raised instead.

object.__radd__(self, other)
object.__rsub__(self, other)
object.__rmul__(self, other)
object.__rdiv__(self, other)
object.__rtruediv__(self, other)
object.__rfloordiv__(self, other)
object.__rmod__(self, other)
object.__rdivmod__(self, other)
object.__rpow__(self, other)
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 left operand does not support the corresponding operation and the operands are of different types. 2 For instance, to evaluate the expression x - y, where y is an instance of a class that has an __rsub__() method, y.__rsub__(x) is called if x.__sub__(y) returns NotImplemented.

삼 항 pow()__rpow__() 를 호출하려고 시도하지 않음에 주의해야 한다 (그렇게 하려면 코어션 규칙이 너무 복잡해진다).

참고

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

object.__iadd__(self, other)
object.__isub__(self, other)
object.__imul__(self, other)
object.__idiv__(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, the augmented assignment falls back to the normal methods. For instance, to execute the statement x += y, where x is an instance of a class that has an __iadd__() method, x.__iadd__(y) is called. If x is an instance of a class that does not define a __iadd__() method, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y.

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

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

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

Called to implement the built-in functions complex(), int(), long(), and float(). Should return a value of the appropriate type.

object.__oct__(self)
object.__hex__(self)

Called to implement the built-in functions oct() and hex(). Should return a string value.

object.__index__(self)

Called to implement operator.index(). Also called whenever Python needs an integer object (such as in slicing). Must return an integer (int or long).

버전 2.5에 추가.

object.__coerce__(self, other)

Called to implement 《mixed-mode》 numeric arithmetic. Should either return a 2-tuple containing self and other converted to a common numeric type, or None if conversion is impossible. When the common type would be the type of other, it is sufficient to return None, since the interpreter will also ask the other object to attempt a coercion (but sometimes, if the implementation of the other type cannot be changed, it is useful to do the conversion to the other type here). A return value of NotImplemented is equivalent to returning None.

3.4.9. Coercion rules

This section used to document the rules for coercion. As the language has evolved, the coercion rules have become hard to document precisely; documenting what one version of one particular implementation does is undesirable. Instead, here are some informal guidelines regarding coercion. In Python 3, coercion will not be supported.

  • If the left operand of a % operator is a string or Unicode object, no coercion takes place and the string formatting operation is invoked instead.

  • It is no longer recommended to define a coercion operation. Mixed-mode operations on types that don’t define coercion pass the original arguments to the operation.

  • New-style classes (those derived from object) never invoke the __coerce__() method in response to a binary operator; the only time __coerce__() is invoked is when the built-in function coerce() is called.

  • For most intents and purposes, an operator that returns NotImplemented is treated the same as one that is not implemented at all.

  • Below, __op__() and __rop__() are used to signify the generic method names corresponding to an operator; __iop__() is used for the corresponding in-place operator. For example, for the operator 〈+〉, __add__() and __radd__() are used for the left and right variant of the binary operator, and __iadd__() for the in-place variant.

  • For objects x and y, first x.__op__(y) is tried. If this is not implemented or returns NotImplemented, y.__rop__(x) is tried. If this is also not implemented or returns NotImplemented, a TypeError exception is raised. But see the following exception:

  • Exception to the previous item: if the left operand is an instance of a built-in type or a new-style class, and the right operand is an instance of a proper subclass of that type or class and overrides the base’s __rop__() method, the right operand’s __rop__() method is tried before the left operand’s __op__() method.

    This is done so that a subclass can completely override binary operators. Otherwise, the left operand’s __op__() method would always accept the right operand: when an instance of a given class is expected, an instance of a subclass of that class is always acceptable.

  • When either operand type defines a coercion, this coercion is called before that type’s __op__() or __rop__() method is called, but no sooner. If the coercion returns an object of a different type for the operand whose coercion is invoked, part of the process is redone using the new object.

  • When an in-place operator (like 〈+=〉) is used, if the left operand implements __iop__(), it is invoked without any coercion. When the operation falls back to __op__() and/or __rop__(), the normal coercion rules apply.

  • In x + y, if x is a sequence that implements sequence concatenation, sequence concatenation is invoked.

  • In x * y, if one operand is a sequence that implements sequence repetition, and the other is an integer (int or long), sequence repetition is invoked.

  • Rich comparisons (implemented by methods __eq__() and so on) never use coercion. Three-way comparison (implemented by __cmp__()) does use coercion under the same conditions as other binary operations use it.

  • In the current implementation, the built-in numeric types int, long, float, and complex do not use coercion. All these types implement a __coerce__() method, for use by the built-in coerce() function.

    버전 2.7에서 변경: The complex type no longer makes implicit calls to the __coerce__() method for mixed-type binary arithmetic operations.

3.4.10. with 문 컨텍스트 관리자

버전 2.5에 추가.

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

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

컨텍스트 관리자에 대한 더 자세한 정보는 컨텍스트 관리자 형 에 나온다.

object.__enter__(self)

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

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

이 객체와 연관된 실행시간 컨텍스트를 종료한다. 파라미터들은 컨텍스트에서 벗어나게 만든 예외를 기술한다. 만약 컨텍스트가 예외 없이 종료한다면, 세 인자 모두 None 이 된다.

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

__exit__() 메서드가 전달된 예외를 다시 일으키지(reraise) 않도록 주의해야 한다; 이것은 호출자(caller)의 책임이다.

더 보기

PEP 343 - 《with》 문

파이썬 with 문에 대한 규격, 배경, 예.

3.4.11. Special method lookup for old-style classes

For old-style classes, special methods are always looked up in exactly the same way as any other method or attribute. This is the case regardless of whether the method is being looked up explicitly as in x.__getitem__(i) or implicitly as in x[i].

This behaviour means that special methods may exhibit different behaviour for different instances of a single old-style class if the appropriate special attributes are set differently:

>>> class C:
...     pass
...
>>> c1 = C()
>>> c2 = C()
>>> c1.__len__ = lambda: 5
>>> c2.__len__ = lambda: 9
>>> len(c1)
5
>>> len(c2)
9

3.4.12. Special method lookup for new-style classes

For new-style classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary. That behaviour is the reason why the following code raises an exception (unlike the equivalent example with old-style classes):

>>> class C(object):
...     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()

이런 동작의 배경에 깔린 논리는, 모든 객체(형 객체를 포함해서)들에 의해 구현되는 __hash__()__repr__() 과 같은 많은 특수 메서드들과 관련이 있다. 만약 이 메서드들에 대한 묵시적인 조회가 일반적인 조회 프로세스를 거친다면, 형 객체 자체에 대해 호출되었을 때 실패하게 된다:

>>> 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

올바름을 추구하기 위해 인스턴스 어트리뷰트들을 우회하는 것에 더해, 묵시적인 특수 메서드 조회는 객체의 메타 클래스의 __getattribute__() 메서드 조차도 우회한다:

>>> 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

이런 식으로 __getattribute__() 절차를 우회하는 것은 특수 메서드 처리의 유연함을 일부 포기하는 대신(특수 메서드가 인터프리터에 의해 일관성 있게 호출되기 위해서는 반드시 클래스 객체에 설정되어야 한다), 인터프리터 내부에서의 속도 최적화를 위한 상당한 기회를 제공한다.

각주

1

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

2

피연산자들이 같은 형이면, 뒤집히지 않은 메서드(__add__() 같은)가 실패하면 그 연산이 지원되지 않는 것으로 간주한다. 이것이 뒤집힌 메서드가 호출되지 않는 이유다.