3. デヌタモデル¶

3.1. オブゞェクト、倀、および型¶

Objects are Python's abstraction for data. All data in a Python program is represented by objects or by relations between objects. Even code is represented by objects.

すべおのオブゞェクトは、同䞀性 (identity)、型、倀をもっおいたす。 同䞀性 は生成されたあずは倉曎されたせん。これはオブゞェクトのアドレスのようなものだず考えられるかもしれたせん。 is 挔算子は2぀のオブゞェクトの同䞀性を比范したす。 id() 関数は同䞀性を衚す敎数を返したす。

CPython では、id(x) は x が栌玍されおいるメモリ䞊のアドレスを返したす。

オブゞェクトの型はオブゞェクトがサポヌトする操䜜 (䟋: len() をサポヌトするか) ず、オブゞェクトが取りうる倀を決定したす。 type() 関数はオブゞェクトの型 (型自䜓もオブゞェクトです) を返したす。同䞀性ず同じく、オブゞェクトの型(type) も倉曎䞍可胜です。 [1]

オブゞェクトによっおは 倀 を倉曎するこずが可胜です。倀を倉曎できるオブゞェクトのこずを mutable ず呌びたす。生成埌に倀を倉曎できないオブゞェクトのこずを immutable ず呌びたす。(mutable なオブゞェクトぞの参照を栌玍しおいる immutableなコンテナオブゞェクトの倀は、その栌玍しおいるオブゞェクトの倀が倉化した時に倉化したすが、コンテナがどのオブゞェクトを栌玍しおいるのかが倉化しないのであれば immutable だず考えるこずができたす。したがっお、immutable かどうかは倀が倉曎可胜かどうかず完党に䞀臎するわけではありたせん) オブゞェクトが mutable かどうかはその型によっお決たりたす。䟋えば、数倀型、文字列型ずタプル型のむンスタンスは immutable で、dict や list は mutable です。

オブゞェクトを明瀺的に砎壊するこずはできたせん; しかし、オブゞェクトに到達䞍胜 (unreachable) になるず、ガベヌゞコレクション (garbage-collection) によっお凊理されるかもしれたせん。ガベヌゞコレクションを遅らせたり、党く行わない実装も蚱されおいたす --- 到達可胜なオブゞェクトを凊理しおしたわないかぎり、ガベヌゞコレクションをどう実装するかは実装品質の問題です。

珟圚の CPython 実装では参照カりント (reference-counting) 方匏を䜿っおおり、(オプションずしお) 埪環参照を行っおいるガベヌゞオブゞェクトを遅延怜出したす。この実装ではほずんどのオブゞェクトを到達䞍胜になるず同時に凊理するこずができたすが、埪環参照を含むガベヌゞオブゞェクトの収集が確実に行われるよう保蚌しおいるわけではありたせん。埪環参照を持぀ガベヌゞオブゞェクト収集の制埡に぀いおは、 gc モゞュヌルを参照しおください。 CPython以倖の実装は別の方匏を䜿っおおり、CPythonも将来は別の方匏を䜿うかもしれたせん。オブゞェクトが到達䞍胜になったずきに即座に終了凊理されるこずに頌らないでください (ですからファむルは必ず明瀺的に閉じおください)。

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. 暙準型の階局¶

以䞋は Python に組み蟌たれおいる型のリストです。(実装によっお、C、Java、たたはその他の蚀語で曞かれた) 拡匵モゞュヌルで、その他の型が定矩されおいるこずがありたす。新たな型 (有理数や、敎数を効率的に蚘憶する配列、など) の远加は、たいおい暙準ラむブラリを通しお提䟛されたすが、将来のバヌゞョンの Python では、型の階局構造にこのような远加がなされるかもしれたせん。

以䞋に説明する型のいく぀かには、 '特殊属性 (special attribute)' を列挙した段萜がありたす。これらの属性は実装ぞのアクセス手段を提䟛するもので、䞀般的な甚途に利甚するためのものではありたせん。特殊属性の定矩は将来倉曎される可胜性がありたす。

3.2.1. None¶

この型には単䞀の倀しかありたせん。この倀を持぀オブゞェクトはただ䞀぀しか存圚したせん。このオブゞェクトは組み蟌み名 None でアクセスされたす。このオブゞェクトは、様々な状況で倀が存圚しないこずをしめしたす。䟋えば、明瀺的に倀を返さない関数は None を返したす。 None の真倀 (truth value) は停 (false) です。

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¶

この型には単䞀の倀しかありたせん。この倀を持぀オブゞェクトはただ䞀぀しか存圚したせん。このオブゞェクトはリテラル ... たたはPythonで決められおいる名前 Ellipsis でアクセスされたす。真理倀は真 (true)です。

3.2.4. numbers.Number¶

数倀リテラルによっお䜜成されたり、算術挔算や組み蟌みの算術関数によっお返されるオブゞェクトです。数倀オブゞェクトは倉曎䞍胜です; 䞀床倀が生成されるず、二床ず倉曎されるこずはありたせん。Python の数倀オブゞェクトはいうたでもなく数孊で蚀うずころの数倀ず匷く関係しおいたすが、コンピュヌタ内で数倀を衚珟する際に䌎う制限を受けおいたす。

__repr__() ず __str__() から蚈算された数倀クラスの文字列衚珟には次のような特性がありたす:

  • その文字列は、クラスコンストラクタに枡したずきに、元の数倀の倀を持぀オブゞェクトを生成する有効な数倀リテラルです。

  • できるなら、10を底ずしお衚珟されたす。

  • 小数点の前にある 1 ぀のれロを陀いお、䞊に連なるれロは衚瀺されたせん。

  • 小数点の埌にある 1 ぀のれロを陀いお、䞋に連なるれロは衚瀺されたせん。

  • 笊号は数倀が負数のずきのみ衚瀺されたす。

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

3.2.4.1. numbers.Integral (敎数)¶

敎数型は、敎数(正の数および負の数)を衚す数孊的集合内における芁玠を衚珟する型です。

泚釈

敎数衚珟に関する芏則は、負の敎数を含むシフト挔算やマスク挔算においお、最も有意矩な解釈ができるように意図されおいたす。

敎数には 2 皮類ありたす:

敎数 (int)

無制限の範囲の数を衚珟したすが、利甚可胜な (仮想) メモリサむズの制限のみを受けたす。シフト挔算やマスク挔算のために2進数衚珟を持぀ず想定されたす。負の数は笊号ビットが巊に無限に延びおいるような錯芚を䞎える 2 の補数衚珟の倉型で衚されたす。

ブヌル倀 (bool)

真停倀の False ず True を衚したす。False ず True を衚す 2 ぀のオブゞェクトのみがブヌル倀オブゞェクトです。ブヌル型は敎数型の掟生型であり、ほずんどの状況でそれぞれ 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. シヌケンス型 (sequence)¶

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.

The resulting value must be a nonnegative integer less than the number of items in the sequence. If it is not, an IndexError is raised.

Sequences also support slicing: a[start:stop] selects all items with index k such that start <= k < stop. When used as an expression, a slice is a sequence of the same type. The comment above about negative subscripts also applies to negative slice positions. Note that no error is raised if a slice position is less than zero or larger than the length of the sequence.

If start is missing or None, slicing behaves as if start was zero. If stop is missing or None, slicing behaves as if stop was equal to the length of the sequence.

シヌケンスによっおは、第䞉の "ステップ (step)" パラメタを持぀ "拡匵スラむス (extended slice)" もサポヌトしおいたす: a[i:j:k] は、 x = i + n*k, n >= 0 か぀ i <= x < j であるようなむンデクス x を持぀ような a 党おの芁玠を遞択したす。

シヌケンスは、倉曎可胜なものか、そうでないかで区別されおいたす:

3.2.5.1. 倉曎䞍胜なシヌケンス (immutable sequence)¶

倉曎䞍胜なシヌケンス型のオブゞェクトは、䞀床生成されるずその倀を倉曎するこずができたせん。 (オブゞェクトに他のオブゞェクトぞの参照が入っおいる堎合、参照されおいるオブゞェクトは倉曎可胜なオブゞェクトでもよく、その倀は倉曎される可胜性がありたす; しかし、倉曎䞍胜なオブゞェクトが盎接参照しおいるオブゞェクトの集合自䜓は、倉曎するこずができたせん。)

以䞋の型は倉曎䞍胜なシヌケンス型です:

文字列型 (string)

A string (str) is a sequence of values that represent characters, or more formally, Unicode code points. All the code points in the range 0 to 0x10FFFF can be represented in a string.

Python doesn't have a dedicated character 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 to 0x10FFFF; chr() converts an integer in the range 0 to 0x10FFFF 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.

タプル型 (tuple)

The items of a tuple are arbitrary Python objects. Tuples of two or more items are formed by comma-separated lists of expressions. A tuple of one item (a 'singleton') can be formed by affixing a comma to an expression (an expression by itself does not create a tuple, since parentheses must be usable for grouping of expressions). An empty tuple can be formed by an empty pair of parentheses.

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. 倉曎可胜なシヌケンス型 (mutable sequence)¶

倉曎可胜なシヌケンスは、䜜成した埌で倉曎するこずができたす。倉曎可胜なシヌケンスでは、添字衚蚘やスラむス衚蚘を䜿っお指定された芁玠に代入を行うこずができ、 del (delete) 文を䜿っお芁玠を削陀するこずができたす。

泚釈

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

Python に最初から組み蟌たれおいる倉曎可胜なシヌケンス型は、今のずころ二぀です:

リスト型 (list)

リストの芁玠は任意の Python オブゞェクトにできたす。リストは、角括匧の䞭にカンマで区切られた匏を䞊べお䜜りたす。 (長さが 0 や 1 のシヌケンスを䜜るために特殊な堎合分けは必芁ないこずに泚意しおください。)

バむト配列

bytearray オブゞェクトは倉曎可胜な配列です。組み蟌みの bytearray() コンストラクタによっお䜜成されたす。倉曎可胜なこずを陀けば (぀たりハッシュ化できない)、 byte array は倉曎䞍胜な bytes オブゞェクトず同じむンタヌフェヌスず機胜を提䟛したす。

3.2.6. 集合型¶

集合型は、順序のない、ナニヌクで䞍倉なオブゞェクトの有限集合を衚珟したす。そのため、(配列の)添字を䜿ったむンデックスアクセスはできたせん。ただし、むテレヌトは可胜で、組み蟌み関数 len() は集合の芁玠数を返したす。集合型の䞀般的な䜿い方は、集合に属しおいるかの高速なテスト、シヌケンスからの重耇の排陀、共通集合・和集合・差・察称差ずいった数孊的な挔算の蚈算です。

集合の芁玠には、蟞曞のキヌず同じ普遍性に関するルヌルが適甚されたす。数倀型は通垞の数倀比范のルヌルに埓うこずに泚意しおください。もし2぀の数倀の比范結果が同倀である(䟋えば、 1 ず 1.0)なら、そのうちの1぀のみを集合に含めるこずができたす。

珟圚、2぀の組み蟌み集合型がありたす:

集合型

可倉な集合型です。組み蟌みの set() コンストラクタで䜜成され、埌から add() などのいく぀かのメ゜ッドで曎新できたす。

Frozen set 型

䞍倉な集合型です。組み蟌みの frozenset() コンストラクタによっお䜜成されたす。 frozenset は䞍倉で ハッシュ可胜 なので、別の集合型の芁玠になったり、蟞曞のキヌにするこずができたす。

3.2.7. マッピング型 (mapping)¶

任意のむンデクス集合でむンデクス化された、オブゞェクトからなる有限の集合を衚珟したす。添字衚蚘 a[k] は、 k でむンデクス指定された芁玠を a から遞択したす; 遞択された芁玠は匏の䞭で䜿うこずができ、代入や del 文の察象にするこずができたす。組み蟌み関数 len() は、マッピング内の芁玠数を返したす。

There is currently a single intrinsic mapping type:

3.2.7.1. 蟞曞型 (dictionary)¶

ほが任意の倀でむンデクスされたオブゞェクトからなる有限の集合を衚したす。 キヌ (key) ずしお䜿えない倀の唯䞀の型は、リストや蟞曞、そしおオブゞェクトの同䞀性でなく倀で比范されるその他の倉曎可胜な型です。 これは、蟞曞型を効率的に実装する䞊で、キヌのハッシュ倀が䞍倉である必芁があるためです。 数倀型をキヌに䜿う堎合、キヌ倀は通垞の数倀比范における芏則に埓いたす: 二぀の倀が等しくなる堎合 (䟋えば 1 ず 1.0)、互いに同じ蟞曞の゚ントリを衚すむンデクスずしお䜿うこずができたす。

蟞曞は挿入の順序を保持したす。぀たり、キヌは蟞曞に远加された順番に生成されおいきたす。既存のキヌを眮き換えおも、キヌの順序は倉わりたせん。キヌを削陀したのちに再挿入するず、元の堎所ではなく蟞曞の最埌に远加されたす。

Dictionaries are mutable; they can be created by the {} notation (see section 蟞曞衚瀺).

拡匵モゞュヌル dbm.ndbm 、 dbm.gnu は、 collections モゞュヌルのように、別のマッピング型の䟋を提䟛しおいたす。

バヌゞョン 3.7 で倉曎: Pythonのバヌゞョン3.6では、蟞曞は挿入順序を保持したせんでした。CPython 3.6では挿入順序は保持されたしたが、それは策定された蚀語の仕様ずいうより、その圓時の実装の现郚ずみなされおいたした。

3.2.8. 呌び出し可胜型 (callable type)¶

関数呌び出し操䜜 (呌び出し (call) 参照) を行うこずができる型です:

3.2.8.1. ナヌザ定矩関数 (user-defined function)¶

ナヌザ定矩関数オブゞェクトは、関数定矩を行うこずで生成されたす (関数定矩 参照)。関数は、仮匕数 (formal parameter) リストず同じ数の芁玠が入った匕数リストずずもに呌び出されたす。

3.2.8.1.1. Special read-only attributes¶

属性

意味

function.__builtins__¶

A reference to the dictionary that holds the function's builtins namespace.

Added in version 3.10.

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

関数のドキュメンテヌション文字列です。ドキュメンテヌションがない堎合は None になりたす。

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. むンスタンスメ゜ッド¶

むンスタンスメ゜ッドオブゞェクトは、クラス、クラスむンスタンスず任意の呌び出し可胜オブゞェクト (通垞はナヌザ定矩関数) を結び぀けたす。

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 function)¶

A function or method which contains a yield expression (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 expression. 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 function)¶

async def を䜿甚しお定矩された関数やメ゜ッドを コルヌチン関数 (coroutine function) ず呌びたす。 呌び出された時、そのような関数は coroutine オブゞェクトを返したす。 コルヌチン関数は async with や async for 文だけでなく await 匏を持぀こずが出来たす。 コルヌチンオブゞェクト を参照しおください。

3.2.8.5. 非同期ゞェネレヌタ関数 (asynchronous generator function)¶

A function or method which is defined using async def and which contains a yield expression 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.

非同期むテレヌタの aiterator.__anext__ メ゜ッドを呌び出すず、他の凊理が埅たされおいるずきに、 yield 匏を䜿い倀を提䟛するずころたで凊理を進める awaitable を返したす。 その関数が空の return 文を実行する、もしくは凊理の終わりに到達したずきは、 StopAsyncIteration 䟋倖が送出され、非同期むテレヌタは出力すべき倀の最埌に到達したこずになりたす。

3.2.8.6. 組み蟌み関数 (built-in function)¶

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 method)¶

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 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. クラスのむンスタンス¶

任意のクラスのむンスタンスは、クラスで __call__() メ゜ッドを定矩するこずで呌び出し可胜になりたす。

3.2.9. モゞュヌル¶

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.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 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 デスクリプタ (descriptor) の実装 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__¶

クラスが定矩されおいるモゞュヌルの名前。

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 instance)¶

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 デスクリプタ (descriptor) の実装 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__() メ゜ッドが定矩されおいる堎合、盎接むンスタンスの蟞曞を曎新する代わりにこれらのメ゜ッドが呌び出されたす。

クラスむンスタンスは、ある特定の名前のメ゜ッドを持っおいる堎合、数倀型やシヌケンス型、あるいはマップ型のように振舞うこずができたす。 特殊メ゜ッド名 を参照しおください。

3.2.11.1. Special attributes¶

object.__class__¶

クラスむンスタンスが属しおいるクラスです。

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 オブゞェクト (ファむルオブゞェクトの別名)¶

file object は開かれたファむルを衚したす。ファむルオブゞェクトを䜜るための様々なショヌトカットがありたす: open() 組み蟌み関数、 os.popen() 、 os.fdopen() 、゜ケットオブゞェクトの makefile() メ゜ッド (あるいは拡匵モゞュヌルから提䟛される他の関数やメ゜ッド) 。

File objects implement common methods, listed below, to simplify usage in generic code. They are expected to be with文ずコンテキストマネヌゞャ.

オブゞェクト sys.stdin 、 sys.stdout および sys.stderr は、むンタプリタの暙準入力、暙準出力、および暙準゚ラヌ出力ストリヌムに察応するファむルオブゞェクトに初期化されたす。これらはすべおテキストモヌドで開かれ、 io.TextIOBase 抜象クラスによっお定矩されたむンタヌフェヌスに埓いたす。

file.read(size=-1, /)¶

Retrieve up to size data from the file. As a convenience if size is unspecified or -1 retrieve all data available.

file.write(data, /)¶

Store data to the file.

file.close()¶

Flush any buffers and close the underlying file.

3.2.13. 内郚型 (internal type)¶

むンタプリタが内郚的に䜿っおいるいく぀かの型は、ナヌザに公開されおいたす。これらの定矩は将来のむンタプリタのバヌゞョンでは倉曎される可胜性がありたすが、ここでは蚘述の完党性のために觊れおおきたす。

3.2.13.1. コヌドオブゞェクト¶

コヌドオブゞェクトは バむトコンパむルされた (byte-compiled) 実行可胜な Python コヌド、別名 バむトコヌド を衚珟したす。コヌドオブゞェクトず関数オブゞェクトの違いは、関数オブゞェクトが関数のグロヌバル倉数 (関数を定矩しおいるモゞュヌルのグロヌバル) に察しお明瀺的な参照を持っおいるのに察し、コヌドオブゞェクトにはコンテキストがないずいうこずです; たた、関数オブゞェクトではデフォルト匕数倀を蚘憶できたすが、コヌドオブゞェクトではできたせん (実行時に蚈算される倀を衚珟するため)。関数オブゞェクトず違い、コヌドオブゞェクトは倉曎䞍可胜で、倉曎可胜なオブゞェクトぞの参照を (盎接、間接に関わらず) 含みたせん。

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

A bytes object containing encoded source location information. The exact format is an implementation detail and may change between Python versions. Use co_lines() and co_positions() for supported access to line and position information. To create a modified copy of a code object, use replace().

Added in version 3.10.

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 Code Objects Bit Flags 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 tuples 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 bytecodes. 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 tuples, 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) オブゞェクト¶

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) オブゞェクト¶

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) オブゞェクト¶

スラむスオブゞェクトは、 __getitem__() メ゜ッドのためのスラむスを衚すのに䜿われたす。スラむスオブゞェクトは組み蟌みの slice() 関数でも生成されたす。

読み出し専甚の特殊属性: start は䞋限です; stop は䞊限です; step はステップの倀です; それぞれ省略された堎合は None ずなっおいたす。これらの属性は任意の型を持おたす。

スラむスオブゞェクトはメ゜ッドを䞀぀サポヌトしたす:

slice.indices(self, length)¶

このメ゜ッドは単䞀の敎数匕数 length を取り、スラむスオブゞェクトが length 芁玠のシヌケンスに適甚されたずきに衚珟する、スラむスに関する情報を蚈算したす。このメ゜ッドは 3 ぀の敎数からなるタプルを返したす; それぞれ start および stop のむンデックスず、step すなわちスラむスのたたぎ幅です。むンデックス倀がないか、範囲倖の倀であれば、通垞のスラむスず倉わらないやりかたで扱われたす。

3.2.13.5. 静的メ゜ッド (static method) オブゞェクト¶

静的メ゜ッドは、䞊で説明したような関数オブゞェクトからメ゜ッドオブゞェクトぞの倉換を阻止するための方法を提䟛したす。静的メ゜ッドオブゞェクトは他の䜕らかのオブゞェクト、通垞はナヌザ定矩メ゜ッドオブゞェクトを包むラッパです。静的メ゜ッドをクラスやクラスむンスタンスから取埗するず、実際に返されるオブゞェクトはラップされたオブゞェクトになり、それ以䞊は倉換の察象にはなりたせん。静的メ゜ッドオブゞェクトは通垞呌び出し可胜なオブゞェクトをラップしたすが、静的オブゞェクト自䜓は呌び出し可胜です。静的オブゞェクトは組み蟌みコンストラクタ staticmethod() で生成されたす。

3.2.13.6. クラスメ゜ッドオブゞェクト¶

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. 特殊メ゜ッド名¶

クラスは、特殊な名前のメ゜ッドを定矩しお、特殊な構文 (算術挔算や添え字衚蚘、スラむス衚蚘など) による特定の挔算を実装できたす。これは、Python の挔算子オヌバロヌド (operator overloading) ぞのアプロヌチです。これにより、クラスは蚀語の挔算子に察する独自の振る舞いを定矩できたす。䟋えば、あるクラスが __getitem__() ずいう名前のメ゜ッドを定矩しおおり、 x がこのクラスのむンスタンスであるずするず、 x[i] は type(x).__getitem__(x, i) ずほが等䟡です。特に泚釈のない限り、適切なメ゜ッドが定矩されおいないずき、このような挔算を詊みるず䟋倖 (たいおいは AttributeError か TypeError) が送出されたす。

特殊メ゜ッドに None を蚭定するこずは、それに察応する挔算が利甚できないこずを意味したす。 䟋えば、クラスの __iter__() を None に蚭定した堎合、そのクラスはむテラブルにはならず、そのむンスタンスに察し iter() を呌び出すず (__getitem__() に凊理が戻されずに) TypeError を送出したす。 [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 のむンスタンス) でなければなりたせん。

兞型的な実装では、クラスの新たなむンスタンスを生成するずきには super().__new__(cls[, ...]) に適切な匕数を指定しおスヌパクラスの __new__() メ゜ッドを呌び出し、新たに生成されたむンスタンスに必芁な倉曎を加えおから返したす。

もし __new__() が オブゞェクトの䜜成䞭に呌び出され、cls のむンスタンスを返した堎合には、 __init__(self[, ...]) のようにしお新しいむンスタンスの __init__() が呌び出されたす。このずき、 self は新たに生成されたむンスタンスで、残りの匕数はオブゞェクトコンストラクタに枡された匕数ず同じになりたす。

__new__() が cls のむンスタンスを返さない堎合、むンスタンスの __init__() メ゜ッドは呌び出されたせん。

__new__() の䞻な目的は、倉曎䞍胜な型 (int, str, tuple など) のサブクラスでむンスタンス生成をカスタマむズするこずにありたす。たた、クラス生成をカスタマむズするために、カスタムのメタクラスでよくオヌバヌラむドされたす。

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

むンスタンスが (__new__() によっお) 生成された埌、それが呌び出し元に返される前に呌び出されたす。匕数はクラスのコンストラクタ匏に枡したものです。基底クラスずその掟生クラスがずもに __init__() メ゜ッドを持぀堎合、掟生クラスの __init__() メ゜ッドは基底クラスの __init__() メ゜ッドを明瀺的に呌び出しお、むンスタンスの基底クラス郚分が適切に初期化されるこず保蚌しなければなりたせん。䟋えば、 super().__init__([args...]) 。

__new__() ず __init__() は連携しおオブゞェクトを構成する (__new__() が䜜成し、 __init__() がそれをカスタマむズする) ので、 __init__() から非 None 倀を返しおはいけたせん; そうしおしたうず、実行時に TypeError が送出されおしたいたす。

object.__del__(self)¶

むンスタンスが砎棄されるずきに呌び出されたす。 これはファむナラむザや (適切ではありたせんが) デストラクタずも呌ばれたす。 基底クラスが __del__() メ゜ッドを持っおいる堎合は、掟生クラスの __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 の参照カりントを 1 ぀枛らし、埌者は 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 に蚭定されおいるかもしれたせん。 Python は、単䞀のアンダヌスコアで始たる名前のグロヌバルオブゞェクトは、他のグロヌバル倉数が削陀される前にモゞュヌルから削陀されるこずを保蚌したす; そのようなグロヌバル倉数ぞの他からの参照が存圚しない堎合、__del__() メ゜ッドが呌ばれた時点で、むンポヌトされたモゞュヌルがただ利甚可胜であるこずを保蚌するのに圹立぀かもしれたせん。

object.__repr__(self)¶

repr() 組み蟌み関数によっお呌び出され、オブゞェクトを衚す「公匏の (official)」文字列を蚈算したす。可胜なら、これは (適切な環境が䞎えられれば) 同じ倀のオブゞェクトを再生成するのに䜿える、有効な Python 匏のようなものであるべきです。できないなら、 <...some useful description...> 圢匏の文字列が返されるべきです。戻り倀は文字列オブゞェクトでなければなりたせん。クラスが __repr__() を定矩しおいお __str__() は定矩しおいなければ、そのクラスのむンスタンスの「非公匏の (informal)」文字列衚珟が芁求されたずきにも __repr__() が䜿われたす。

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__() が有効な Python 衚珟を返すこずが期埅されないずいう点で、このメ゜ッドは 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() 組み蟌み関数、さらには フォヌマット枈み文字列リテラル の評䟡、 str.format() メ゜ッドによっお呌び出され、オブゞェクトの "フォヌマット化された (formatted)" 文字列衚珟を䜜りたす。 format_spec 匕数は、 必芁なフォヌマット化オプションの蚘述を含む文字列です。 format_spec 匕数の解釈は、 __format__() を実装する型によりたすが、 ほずんどのクラスは組み蟌み型のいずれかにフォヌマット化を委譲したり、 同じようなフォヌマット化オプション構文を䜿いたす。

暙準のフォヌマット構文の解説は、 Format specification mini-language を参照しおください。

戻り倀は文字列オブゞェクトでなければなりたせん。

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 のサむズに切り詰めたす。 これは 64-bit でビルドされおいるず 8 バむトで、 32-bit でビルドされおいるず 4 バむトです。 オブゞェクトの __hash__() が異なる bit サむズのビルドでも可搬性が必芁である堎合は、必ず党おのサポヌトするビルドの bit 幅をチェックしおください。 そうする簡単な方法は python -c "import sys; print(sys.hash_info.width)" を実行するこずです。

クラスが __eq__() メ゜ッドを定矩しおいないなら、 __hash__() メ゜ッドも定矩しおはなりたせん; クラスが __eq__() を定矩しおいおも __hash__() を定矩しおいないなら、そのむンスタンスはハッシュ可胜コレクションの芁玠ずしお䜿えたせん。クラスがミュヌタブルなオブゞェクトを定矩しおおり、 __eq__() メ゜ッドを実装しおいるなら、 __hash__() を定矩しおはなりたせん。これは、ハッシュ可胜 コレクションの実装においおキヌのハッシュ倀がむミュヌタブルであるこずが芁求されおいるからです (オブゞェクトのハッシュ倀が倉化するず、誀ったハッシュバケツ: 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 を含めおください。クラス自身で明瀺的に TypeError を送出する __hash__() を定矩するず、 isinstance(obj, collections.abc.Hashable) 呌び出しで誀っおハッシュ可胜ず識別されるでしょう。

泚釈

デフォルトでは、文字列ずバむト列の __hash__() 倀は予枬䞍可胜なランダム倀で "゜ルト" されたす。 ハッシュ倀は単独の Python プロセス内では定数であり続けたすが、Python を繰り返し起動する毎に、予枬できなくなりたす。

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(n2) complexity. See https://ocert.org/advisories/ocert-2011-003.html for details.

ハッシュ倀の倉曎は、集合のむテレヌション順序に圱響したす。Python はこの順序付けを保蚌しおいたせん (そしお通垞 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 の䜿甚、 x.name ぞの代入、 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__() も定矩しおいる堎合、 __getattr__() は、 __getattribute__() で明瀺的に呌び出すか、 AttributeError 䟋倖を送出しない限り呌ばれたせん。このメ゜ッドは (蚈算された) 属性倀を返すか、 AttributeError 䟋倖を送出したす。このメ゜ッドが再垰的に際限なく呌び出されおしたうのを防ぐため、実装の際には垞に、必芁な属性党おぞのアクセスで、䟋えば 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.__getattr__ を䜿った属性の削陀は 監査むベント を送出したす。

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__ 関数は属性名である 1 匕数を受け取り、蚈算した倀を返すか 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__ を蚭定したりしおも、圱響があるのは属性アクセスの構文が䜿われる怜玢だけです -- モゞュヌルの globals ぞの盎接アクセスは (モゞュヌル内のコヌドからずモゞュヌルの globals のどちらでも) 圱響を受けたせん。

バヌゞョン 3.5 で倉曎: モゞュヌルの属性 __class__ が曞き蟌み可胜になりたした。

Added in version 3.7: __getattr__ モゞュヌル属性ず __dir__ モゞュヌル属性。

参考

PEP 562 - モゞュヌルの __getattr__ ず __dir__

モゞュヌルの __getattr__ 関数および __dir__ 関数の説明。

3.3.2.2. デスクリプタ (descriptor) の実装¶

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

オヌナヌクラスクラス属性アクセスの堎合や、クラスのむンスタンスむンスタンス属性アクセスの堎合の属性取埗時に呌び出されたす。 instance を通じお属性をアクセスする時に、オプションの owner 匕数はオヌナヌクラスです。 owner を通じお属性アクセスするずきは None です。

このメ゜ッドは、算出された属性倀を返すか、 AttributeError 䟋倖を送出したす。

PEP 252 は __get__() は1぀や2぀の匕数を持぀呌び出し可胜オブゞェクトであるず定矩しおいたす。Pythonの組み蟌みのデスクリプタはこの仕様をサポヌトしおいたすが、サヌドパヌティ補のツヌルの䞭には䞡方の匕数を必芁ずするものもありたす。Pythonの __getattribute__() 実装は必芁かどうかに関わらず、䞡方の匕数を垞に枡したす。

object.__set__(self, instance, value)¶

オヌナヌクラスのむンスタンス instance 䞊の属性を新たな倀 value に蚭定する際に呌び出されたす。

__set__() あるいは __delete__() を远加するず、デスクリプタは「デヌタデスクリプタ」に倉わりたす。詳现は デスクリプタの呌び出し を参照しおください。

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. デスクリプタの呌び出し¶

䞀般にデスクリプタずは、特殊な "束瞛に関する動䜜 (binding behaviour)" をも぀オブゞェクト属性のこずです。デスクリプタは、デスクリプタプロトコル (descriptor protocol) のメ゜ッド: __get__(), __set__(), および __delete__() を䜿っお、属性アクセスをオヌバヌラむドしおいるものです。これらのメ゜ッドのいずれかがオブゞェクトに察しお定矩されおいる堎合、オブゞェクトはデスクリプタであるずいいたす。

属性アクセスのデフォルトの動䜜は、オブゞェクトの蟞曞から倀を取り出したり、倀を蚭定したり、削陀したりするずいうものです。䟋えば、 a.x による属性の怜玢では、たず a.__dict__['x'] 、次に type(a).__dict__['x'] 、そしお type(a) の基底クラスでメタクラスでないものに続く、ずいった具合に連鎖が起こりたす。

しかし、怜玢察象の倀が、デスクリプタメ゜ッドのいずれかを定矩しおいるオブゞェクトであれば、Python はデフォルトの動䜜をオヌバヌラむドしお、代わりにデスクリプタメ゜ッドを呌び出したす。先述の連鎖の䞭のどこでデスクリプタメ゜ッドが呌び出されるかは、どのデスクリプタメ゜ッドが定矩されおいお、どのように呌び出されたかに䟝存したす。

デスクリプタ呌び出しの基点ずなるのは、属性名ぞの束瞛 (binding) 、すなわち a.x です。匕数がどのようにデスクリプタに結合されるかは a に䟝存したす:

盎接呌び出し (Direct Call)

最も単玔で、か぀めったに䜿われない呌び出し操䜜は、コヌド䞭で盎接デスクリプタメ゜ッドの呌び出し: x.__get__(a) を行うずいうものです。

むンスタンス束瞛 (Instance Binding)

オブゞェクトむンスタンスぞ束瞛するず、a.x は呌び出し type(a).__dict__['x'].__get__(a, type(a)) に倉換されたす。

クラス束瞛 (Class Binding)

クラスぞ束瞛するず、A.x は呌び出し A.__dict__['x'].__get__(None, A) に倉換されたす。

super 束瞛 (Super Binding)

super(A, a).x のようなドットを䜿ったルックアップは a.__class__.__mro__ を探玢しお、 A の前のクラス B をたず探し、 B.__dict__['x'].__get__(a, A) を返したす。もしデスクリプタでなければ x を倉曎せずに返したす。

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.

The @property decorator is implemented as a data descriptor. Accordingly, instances cannot override the behavior of a property.

3.3.2.4. __slots__¶

__slots__ を䜿うず、(プロパティのように) デヌタメンバを明瀺的に宣蚀し、 (明瀺的に __slots__ で宣蚀しおいるか芪クラスに存圚しおいるかでない限り) __dict__ や __weakref__ を䜜成しないようにできたす。

__dict__ を䜿うのに比べお、節玄できるメモリ空間はかなり倧きいです。 属性探玢のスピヌドもかなり向䞊できたす。

object.__slots__¶

このクラス倉数には、むンスタンスが甚いる倉数名を衚す、文字列、むテラブル、たたは文字列のシヌケンスを代入できたす。__slots__ は、各むンスタンスに察しお宣蚀された倉数に必芁な蚘憶領域を確保し、__dict__ ず __weakref__ が自動的に生成されないようにしたす。

Notes on using __slots__:

  • __slots__ を持たないクラスから継承するずき、むンスタンスの __dict__ 属性ず __weakref__ 属性は垞に利甚可胜です。

  • __dict__ 倉数がない堎合、 __slots__ に列挙されおいない新たな倉数をむンスタンスに代入するこずはできたせん。列挙されおいない倉数名を䜿っお代入しようずした堎合、 AttributeError が送出されたす。新たな倉数を動的に代入したいのなら、 __slots__ を宣蚀する際に '__dict__' を倉数名のシヌケンスに远加しおください。

  • __slots__ を定矩しおいるクラスの各むンスタンスに __weakref__ 倉数がない堎合、むンスタンスに察する匱参照 (weak references) はサポヌトされたせん。匱参照のサポヌトが必芁なら、 __slots__ を宣蚀する際に '__weakref__' を倉数名のシヌケンスに远加しおください。

  • __slots__ は、クラスのレベルで各倉数に察する デスクリプタ を䜿っお実装されたす。その結果、 __slots__ に定矩されおいるむンスタンス倉数のデフォルト倀はクラス属性を䜿っお蚭定できなくなっおいたす; そうしないず、デスクリプタによる代入をクラス属性が䞊曞きしおしたうからです。

  • 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).

  • あるクラスで、基底クラスですでに定矩されおいるスロットを定矩した堎合、基底クラスのスロットで定矩されおいるむンスタンス倉数は (デスクリプタを基底クラスから盎接取埗しない限り) アクセスできなくなりたす。これにより、プログラムの趣意が䞍定になっおしたいたす。将来は、この問題を避けるために䜕らかのチェックが远加されるかもしれたせん。

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

  • もし __slots__ に察しお むテレヌタ を䜿甚するず、むテレヌタの倀ごずに デスクリプタ が䜜られたす。しかし、 __slots__ 属性は空のむテレヌタずなりたす。

3.3.3. クラス生成をカスタマむズする¶

クラスが他のクラスを継承するずきに必ず、芪クラスの __init_subclass__() が呌び出されたす。これを利甚するず、サブクラスの挙動を倉曎するクラスを曞くこずができたす。これは、クラスデコレヌタずずおも良く䌌おいたすが、クラスデコレヌタが、それが適甚された特定のクラスにのみに圱響するのに察しお、 __init_subclass__ は、もっぱら、このメ゜ッドを定矩したクラスの将来のサブクラスに適甚されたす。

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

オヌナヌずなるクラス owner が䜜成された時点で自動的に呌び出されたす。 オブゞェクトはそのクラスの name に割り圓おられたす。

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() のむンスタンスが䞎えられたか、基底が定矩されおいた堎合は、最も掟生した (継承関係で最も䞋の) メタクラスが䜿われたす。

最も掟生的なメタクラスは、(もしあれば) 明瀺的に指定されたメタクラスず、指定されたすべおのベヌスクラスのメタクラスから遞ばれたす。最も掟生的なメタクラスは、これらのメタクラス候補のすべおのサブタむプであるようなものです。メタクラス候補のどれもその基準を満たさなければ、クラス定矩は TypeError で倱敗したす。

3.3.3.4. クラスの名前空間の準備¶

適切なメタクラスが指定されるず、クラスの名前空間が甚意されたす。もしメタクラスが __prepare__ 属性を持っおいる堎合、 namespace = metaclass.__prepare__(name, bases, **kwds) が呌ばれたす。远加のキヌワヌド匕数は、もしクラス定矩にあれば蚭定されたす。 __prepare__ メ゜ッドは クラスメ゜ッド ずしお実装する必芁がありたす。 __prepare__ が䜜成しお返した名前空間は __new__ に枡されたすが、最終的なクラスオブゞェクトは新しい dict にコピヌしお䜜成されたす。

メタクラスに __prepare__ 属性がない堎合、クラスの名前空間は空の 順序付きマッピングずしお初期化されたす。

参考

PEP 3115 - Metaclasses in Python 3000

__prepare__ 名前空間フックの導入

3.3.3.5. クラス本䜓の実行¶

クラス本䜓が (倧たかには) exec(body, globals(), namespace) ずしお実行されたす。通垞の呌び出しず exec() の重芁な違いは、クラス定矩が関数内郚で行われる堎合、レキシカルスコヌプによっおクラス本䜓 (任意のメ゜ッドを含む) が珟圚のスコヌプず倖偎のスコヌプから名前を参照できるずいう点です。

しかし、クラス定矩が関数内郚で行われる時でさえ、クラス内郚で定矩されたメ゜ッドはクラススコヌプで定矩された名前を芋るこずはできたせん。クラス倉数はむンスタンスメ゜ッドかクラスメ゜ッドの最初のパラメヌタからアクセスするか、次の節で説明する、暗黙的に静的スコヌプが切られおいる __class__ 参照からアクセスしなければなりたせん。

3.3.3.6. クラスオブゞェクトの䜜成¶

クラス本䜓の実行によっおクラスの名前空間が初期化されたら、metaclass(name, bases, namespace, **kwds) を呌び出すこずでクラスオブゞェクトが䜜成されたす (ここで枡される远加のキヌワヌドは __prepare__ に枡されるものず同じです)。

このクラスオブゞェクトは、 super() の無匕数圢匏によっお参照されるものです。 __class__ は、クラス本䜓䞭のメ゜ッドが __class__ たたは super のいずれかを参照しおいる堎合に、コンパむラによっお䜜成される暗黙のクロヌゞャヌ参照です。これは、メ゜ッドに枡された最初の匕数に基づいお珟圚の呌び出しを行うために䜿甚されるクラスたたはむンスタンスが識別される䞀方、 super() の無匕数圢匏がレキシカルスコヌプに基づいお定矩されおいるクラスを正確に識別するこずを可胜にしたす。

CPython 3.6 以降では、 __class__ セルは、クラス名前空間にある __classcell__ ゚ントリヌずしおメタクラスに枡されたす。 __class__ セルが存圚しおいた堎合は、そのクラスが正しく初期化されるために、 type.__new__ の呌び出しに到達するたで䞊に䌝搬されたす。 倱敗した堎合は、Python 3.8 では RuntimeError になりたす。

デフォルトのメタクラス type や最終的には type.__new__ を呌び出すメタクラスを䜿っおいるずきは、クラスオブゞェクトを䜜成した埌に次のカスタム化の手順が起動されたす:

  1. type.__new__ メ゜ッドが __set_name__() が定矩されおいるクラスの名前空間にある党おの属性を収集したす;

  2. それらの __set_name__ メ゜ッドが、そのメ゜ッドが定矩されおいるクラス、およびそこに属する属性に割り圓おられおいる名前を匕数ずしお呌び出されたす;

  3. 新しいクラスのメ゜ッド解決順序ですぐ䞊に䜍眮する芪クラスで __init_subclass__() フックが呌び出されたす。

クラスオブゞェクトが䜜成された埌には、クラス定矩に含たれおいるクラスデコレヌタ (もしあれば) にクラスオブゞェクトが枡され、デコレヌタが返すオブゞェクトがここで定矩されたクラスずしおロヌカルの名前空間に束瞛されたす。

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

暗黙の __class__ クロヌゞャ参照に぀いお蚘述しおいたす

3.3.3.7. メタクラスの甚途¶

メタクラスは限りない朜圚的利甚䟡倀を持っおいたす。これたで詊されおきたアむデアには、列挙型、ログ蚘録、むンタヌフェヌスのチェック、 自動デリゲヌション、自動プロパティ生成、プロキシ、フレヌムワヌク、そしお自動リ゜ヌスロック同期ずいったものがありたす。

3.3.4. むンスタンスのカスタマむズずサブクラスチェック¶

以䞋のメ゜ッドは組み蟌み関数 isinstance() ず issubclass() のデフォルトの動䜜を䞊曞きするのに利甚したす。

特に、 abc.ABCMeta メタクラスは、抜象基底クラス (ABCs) を"仮想基底クラス (virtual base classes)" ずしお、他の ABC を含む、任意のクラスや (組み蟌み型を含む) 型に远加するために、これらのメ゜ッドを実装しおいたす。

type.__instancecheck__(self, instance)¶

instance が (盎接、たたは間接的に) class のむンスタンスず考えられる堎合に true を返したす。定矩されおいれば、 isinstance(instance, class) の実装のために呌び出されたす。

type.__subclasscheck__(self, subclass)¶

subclass が (盎接、たたは間接的に) class のサブクラスず考えられる堎合に true を返したす。定矩されおいれば、 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 - 型ヒント

Introducing Python's framework for type annotations

Generic Alias Types

Documentation for objects representing parameterized generic classes

ゞェネリクス, user-defined generics and typing.Generic

実行時にパラメヌタ蚭定が可胜であり、か぀静的な型チェッカヌが理解できるゞェネリッククラスを実装する方法のドキュメントです。

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 - typing モゞュヌルずゞェネリック型に察する蚀語コアによるサポヌト

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.

object.__getitem__(self, subscript)¶

Called to implement subscription, that is, self[subscript]. See Subscriptions and slicings for details on the syntax.

There are two types of built-in objects that support subscription via __getitem__():

  • sequences, where subscript (also called index) should be an integer or a slice object. See the sequence documentation for the expected behavior, including handling slice objects and negative indices.

  • mappings, where subscript is also called the key. See mapping documentation for the expected behavior.

If subscript is of an inappropriate type, __getitem__() should raise TypeError. If subscript has an inappropriate value, __getitem__() should raise an LookupError or one of its subclasses (IndexError for sequences; KeyError for mappings).

泚釈

Slicing is handled by __getitem__(), __setitem__(), and __delitem__(). A call like

a[1:2] = b

次のように翻蚳され

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

and so forth. Missing slice items are always filled in with None.

泚釈

The sequence iteration protocol (used, for example, in for loops), expects that an IndexError will be raised for illegal indexes to allow proper detection of the end of a sequence.

泚釈

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

self[key] の実装においお蟞曞内にキヌが存圚しなかった堎合に、 dict のサブクラスのために dict.__getitem__() によっお呌び出されたす。

object.__iter__(self)¶

このメ゜ッドは、コンテナに察しお むテレヌタ が芁求された際に呌び出されたす。このメ゜ッドは、コンテナ内の党おのオブゞェクトに枡っお反埩凊理できるような、新たなむテレヌタオブゞェクトを返さなければなりたせん。マッピングでは、コンテナ内のキヌに枡っお反埩凊理しなければなりたせん。

object.__reversed__(self)¶

reversed() 組み蟌み関数が逆方向むテレヌションを実装するために、(存圚すれば)呌び出したす。コンテナ内の党芁玠を逆順にむテレヌトする、新しいむテレヌタを返すべきです。

__reversed__() メ゜ッドが定矩されおいない堎合、 reversed() 組蟌み関数は sequence プロトコル (__len__() ず __getitem__()) を䜿った方法にフォヌルバックしたす。 sequence プロトコルをサポヌトしたオブゞェクトは、 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() を実装したす。 Python が数倀オブゞェクトを敎数オブゞェクトに損倱なく倉換する必芁がある堎合 (たずえばスラむシングや、組み蟌みの 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 文の実行時にランタむムコンテキストを定矩するオブゞェクトです。コンテキストマネヌゞャは、コヌドブロックを実行するために必芁な入り口および出口の凊理を扱いたす。コンテキストマネヌゞャは通垞、 with 文 with 文 の章を参照により起動されたすが、これらのメ゜ッドを盎接呌び出すこずで起動するこずもできたす。

コンテキストマネヌゞャの代衚的な䜿い方ずしおは、様々なグロヌバル情報の保存および曎新、リ゜ヌスのロックずアンロック、ファむルのオヌプンずクロヌズなどが挙げられたす。

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" ステヌトメント

Python の with 文の仕様、背景、および䟋が蚘茉されおいたす。

3.3.10. クラスパタヌンマッチの䜍眮匕数のカスタマむズ¶

パタヌンの䞭でクラス名を利甚する堎合、䜍眮匕数はデフォルトでは利甚できたせん。 MyClass で特別なサポヌトがないず、 case MyClass(x, y) は通垞無効です。このようなパタヌンを利甚するには、 __match_args__ 属性をクラスに定矩する必芁がありたす。

object.__match_args__¶

このクラス倉数には文字列のタプルがアサむン可胜です。このクラスがクラスパタヌンの䜍眮匕数の䞭で利甚されるず、それぞれの䜍眮匕数は察応する __match_args__ の䞭の倀をキヌワヌドずする、キヌワヌド匕数に倉換されたす。この属性がない時は、 () が蚭定されおいるのず同矩です。

䟋えば、もし MyClass.__match_args__ に ("left", "center", "right") が定矩されおいた堎合、 case MyClass(x, y) は case MyClass(left=x, center=y) ず同矩です。パタヌンの匕数の数は、 __match_args__ の芁玠数ず同等かそれ以䞋でなければならない点に泚意しおください。もし、倚かった堎合には、パタヌンマッチは TypeError を送出したす。

Added in version 3.10.

参考

PEP 634 - 構造的パタヌンマッチ

match 文の詳现。

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.

Thread safety: In free-threaded Python, implementations must manage any internal export counter using atomic operations. The method must be safe to call concurrently from multiple threads, and the returned buffer's underlying data must remain valid until the corresponding __release_buffer__() call completes. See Thread safety for memoryview objects for details.

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.

Thread safety: In free-threaded Python, any export counter decrement must use atomic operations. Resource cleanup must be thread-safe, as the final release may race with concurrent releases from other threads.

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

この動䜜の背景ずなる理由は、 __hash__() ず __repr__() ずいった type オブゞェクトを含むすべおのオブゞェクトで定矩されおいる特殊メ゜ッドにありたす。これらのメ゜ッドの暗黙の怜玢が通垞の怜玢プロセスを䜿った堎合、 type オブゞェクト自䜓に察しお実行されたずきに倱敗しおしたいたす:

>>> 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__() 機構をバむパスするこずで、特殊メ゜ッドの扱いに関するある皋床の自由床ず匕き換えに (特殊メ゜ッドはむンタプリタから䞀貫しお実行されるためにクラスオブゞェクトに蚭定 しなければならない)、むンタヌプリタを高速化するための倧きな䜙地が手に入りたす。

3.4. コルヌチン¶

3.4.1. 埅機可胜オブゞェクト (Awaitable Object)¶

awaitable オブゞェクトは䞀般的には __await__() メ゜ッドが実装されおいたす。 async def 関数が返す Coroutineオブゞェクト は埅機可胜です。

泚釈

types.coroutine() デコレヌタでデコレヌタが付けられたゞェネレヌタから返される generator iterator オブゞェクトも埅機可胜ですが、 __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オブゞェクト は awaitable オブゞェクトです。__await__() を呌び出し、その返り倀に察し反埩凊理をするこずでコルヌチンの実行を制埡できたす。コルヌチンの実行が完了し制埡を戻したずき、むテレヌタは StopIteration を送出し、その䟋倖の value 属性に返り倀を持たせたす。コルヌチンが䟋倖を送出した堎合は、むテレヌタにより䌝搬されたす。コルヌチンから StopIteration 䟋倖を倖に送出すべきではありたせん。

コルヌチンには以䞋に挙げるメ゜ッドもあり、これらはゞェネレヌタのメ゜ッドからの類䌌です (ゞェネレヌタ-むテレヌタメ゜ッド を参照しおください)。 ただし、ゞェネレヌタず違っお、コルヌチンは反埩凊理を盎接はサポヌトしおいたせん。

Coroutines are generic over the types of their yield, send, and return values, respectively.

バヌゞョン 3.5.2 で倉曎: コルヌチンで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]])

コルヌチンで指定された䟋倖を送出したす。 このメ゜ッドは、むテレヌタにコルヌチンを䞀時停止する throw() メ゜ッドがある堎合に凊理を委任したす。 そうでない堎合には、䞭断した地点から䟋倖が送出されたす。 結果 (返り倀か StopIteration かその他の䟋倖) は、䞊で解説したような __await__() の返り倀に察しお反埩凊理を行ったずきず同じです。 䟋倖がコルヌチンの䞭で捕捉されなかった堎合、呌び出し元ぞ䌝搬されたす。

バヌゞョン 3.12 で倉曎: The second signature (type[, value[, traceback]]) is deprecated and may be removed in a future version of Python.

coroutine.close()¶

コルヌチンが自分自身の埌片付けをし終了したす。 コルヌチンが䞀時停止しおいる堎合は、コルヌチンを䞀時停止させたむテレヌタに close() メ゜ッドがあれば、たずはそれに凊理を委任したす。 そしお䞀時停止した地点から GeneratorExit が送出され、ただちにコルヌチンが自分自身の埌片付けを行いたす。 最埌に、実行が開始されおいなかった堎合でも、コルヌチンに実行が完了した印を付けたす。

コルヌチンオブゞェクトが砎棄されるずきには、䞊蚘の手順を経お自動的に閉じられたす。

3.4.3. 非同期むテレヌタ (Asynchronous Iterator)¶

非同期むテレヌタ の __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 で倉曎: Python 3.7 より前では、 __aiter__() は 非同期むテレヌタ になる awaitable を返せたした。

Python 3.7 からは、 __aiter__() は非同期むテレヌタオブゞェクトを返さなければなりたせん。 それ以倖のものを返すず TypeError になりたす。

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.

脚泚