データモデル
************


オブジェクト、値、および型
==========================

Python における *オブジェクト (object)* とは、データを抽象的に表したも
のです。Python プログラムにおけるデータは全て、オブジェクトまたはオブ
ジェクト間の関係として表されます。(ある意味では、プログラムコードもま
たオブジェクトとして表されます。これはフォン・ノイマン: Von Neumann の
「プログラム記憶方式コンピュータ: stored program computer」 のモデルに
適合します。)

Every object has an identity, a type and a value.  An object’s
*identity* never changes once it has been created; you may think of it
as the object’s address in memory.  The 『"is"』 operator compares the
identity of two objects; the "id()" function returns an integer
representing its identity (currently implemented as its address). An
object’s *type* is also unchangeable. [1] An object’s type determines
the operations that the object supports (e.g., 「does it have a
length?」) and also defines the possible values for objects of that
type.  The "type()" function returns an object’s type (which is an
object itself).  The *value* of some objects can change.  Objects
whose value can change are said to be *mutable*; objects whose value
is unchangeable once they are created are called *immutable*. (The
value of an immutable container object that contains a reference to a
mutable object can change when the latter’s value is changed; however
the container is still considered immutable, because the collection of
objects it contains cannot be changed.  So, immutability is not
strictly the same as having an unchangeable value, it is more subtle.)
An object’s mutability is determined by its type; for instance,
numbers, strings and tuples are immutable, while dictionaries and
lists are mutable.

オブジェクトを明示的に破壊することはできません; しかし、オブジェクトに
到達不能 (unreachable) になると、ガベージコレクション (garbage-
collection) によって処理されます。実装では、ごみ収集を遅らせたり、全く
行わないようにすることができます — 到達可能なオブジェクトをごみ収集処
理してしまわないかぎり、どう実装するかは実装品質の問題です。

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

実装のトレース機能やデバッグ機能を使えば、通常は収集されてしまうような
オブジェクトを生存させることがあるので注意してください。また、 『
"try"…"except"』 文を使って例外を捕捉できるようにすると、オブジェクト
を生存させることがあります。

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

他のオブジェクトに対する参照をもつオブジェクトもあります; これらは *コ
ンテナ (container)* と呼ばれます。コンテナオブジェクトの例として、タプ
ル、リスト、および辞書が挙げられます。オブジェクトへの参照自体がコンテ
ナの値の一部です。ほとんどの場合、コンテナの値というと、コンテナに入っ
ているオブジェクトの値のことを指し、それらオブジェクトのアイデンティテ
ィではありません; しかしながら、コンテナの変更可能性について述べる場合
、今まさにコンテナに入っているオブジェクトのアイデンティティのことを指
します。したがって、 (タプルのように) 変更不能なオブジェクトが変更可能
なオブジェクトへの参照を含む場合、その値が変化するのは変更可能なオブジ
ェクトが変更された時、ということになります。

型はオブジェクトの動作のほとんど全てに影響します。オブジェクトのアイデ
ンティティが重要かどうかでさえ、ある意味では型に左右されます: 変更不能
な型では、新たな値を計算するような操作を行うと、実際には同じ型と値を持
った既存のオブジェクトへの参照を返すことがありますが、変更可能なオブジ
ェクトではそのような動作は起こりえません。例えば、 "a = 1; b = 1" とす
ると、 "a" と "b" は値 1 を持つ同じオブジェクトを参照するときもあるし
、そうでないときもあります。これは実装に依存します。しかし、 "c = [];
d = []" とすると、 "c" と "d" はそれぞれ二つの異なった、互いに一意な、
新たに作成された空のリストを参照することが保証されています。 ("c = d =
[]" とすると、 "c" と "d" の両方に同じオブジェクトを代入します)


標準型の階層
============

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

以下に説明する型のいくつかには、 『特殊属性 (special attribute)』 を列
挙した段落があります。これらの属性は実装へのアクセス手段を提供するもの
で、一般的な用途に利用するためのものではありません。特殊属性の定義は将
来変更される可能性があります。

None
   この型には単一の値しかありません。この値を持つオブジェクトはただ一
   つしか存在しません。このオブジェクトは組み込み名 "None" でアクセス
   されます。このオブジェクトは、様々な状況で値が存在しないことをしめ
   します。例えば、明示的に値を返さない関数は "None" を返します。
   "None" の真値 (truth value) は偽 (false) です。

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

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

"numbers.Number"
   数値リテラルによって作成されたり、算術演算や組み込みの算術関数によ
   って返されるオブジェクトです。数値オブジェクトは変更不能です; 一度
   値が生成されると、二度と変更されることはありません。Python の数値オ
   ブジェクトはいうまでもなく数学で言うところの数値と強く関係していま
   すが、コンピュータ内で数値を表現する際に伴う制限を受けています。

   Python は整数、浮動小数点数、複素数の間で区別を行っています:

   "numbers.Integral" (整数)
      整数型は、整数(正の数および負の数)を表す数学的集合内における要素
      を表現する型です。

      There are three types of integers:

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

      Long integers
         無制限の範囲の数を表現しますが、利用可能な (仮想) メモリサイ
         ズの制限のみを受けます。シフト演算やマスク演算のために2進数表
         現を持つと想定されます。負の数は符号ビットが左に無限に延びて
         いるような錯覚を与える 2 の補数表現の変型で表されます。

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

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

   "numbers.Real" ("float") (実数)
      この型は計算機レベルの倍精度浮動小数点数を表現します。表現可能な
      値の範囲やオーバーフローの扱いは計算機のアーキテクチャ（および、
      CやJavaによる実装）に従います。Pythonは単精度浮動小数点数をサポ
      ートしません。一般的に単精度浮動小数点数を使う理由はプロセッサー
      とメモリの使用を節約するためと説明されます。しかし、こうした節約
      はPythonでオブジェクトを扱う際のオーバーヘッドに比べれば微々たる
      ものです。また、2種類の浮動小数点数型を持つことで複雑になる理由
      はありません。

   "numbers.Complex"
      この型は、計算機レベルで倍精度とされている浮動小数点を 2 つ一組
      にして複素数を表現します。浮動小数点について述べたのと同じ性質が
      当てはまります。複素数 "z" の実数部および虚数部は、それぞれ読み
      出し専用属性 "z.real" および "z.imag" で取り出すことができます。

シーケンス型 (sequence)
   この型は、有限の順序集合 (ordered set) を表現します。要素は非負の整
   数でインデクス化されています。組み込み関数 "len()" を使うと、シーケ
   ンスの要素数を返します。シーケンスの長さが *n* の場合、インデクスは
   0, 1, …, *n* -1 からなる集合です。シーケンス *a* の要素 *i* は
   "a[i]" で選択します。

   シーケンスはスライス操作 (slice) もサポートしています: "a[i:j]" と
   すると、 *i* "<=" *k* "<" *j* であるインデクス *k* をもつ全ての要素
   を選択します。式表現としてスライスを用いた場合、スライスは同じ型を
   もつ新たなシーケンスを表します。新たなシーケンス内では、インデクス
   集合が 0 から始まるようにインデクスの値を振りなおします。

   シーケンスによっては、第三の 「ステップ (step)」 パラメタを持つ 「
   拡張スライス (extended slice)」 もサポートしています: "a[i:j:k]" は
   、 "x = i + n*k", *n* ">=" "0" かつ *i* "<=" *x* "<" *j* であるよう
   なインデクス *x* を持つような *a* 全ての要素を選択します。

   シーケンスは、変更可能なものか、そうでないかで区別されています:

   変更不能なシーケンス (immutable sequence)
      変更不能なシーケンス型のオブジェクトは、一度生成されるとその値を
      変更することができません。 (オブジェクトに他のオブジェクトへの参
      照が入っている場合、参照されているオブジェクトは変更可能なオブジ
      ェクトでもよく、その値は変更される可能性があります; しかし、変更
      不能なオブジェクトが直接参照しているオブジェクトの集合自体は、変
      更することができません。)

      以下の型は変更不能なシーケンス型です:

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

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

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

      タプル型 (tuple)
         タプルの要素は任意の Python オブジェクトです。二つ以上の要素
         からなるタプルは、個々の要素を表現する式をカンマで区切って構
         成します。単一の要素からなるタプル (単集合 『singleton』) を
         作るには、要素を表現する式の直後にカンマをつけます (単一の式
         だけではタプルを形成しません。これは、式をグループ化するのに
         丸括弧を使えるようにしなければならないからです)。要素の全くな
         い丸括弧の対を作ると空のタプルになります。

   変更可能なシーケンス型 (mutable sequence)
      変更可能なシーケンスは、作成した後で変更することができます。変更
      可能なシーケンスでは、添字表記やスライス表記を使って指定された要
      素に代入を行うことができ、 "del" (delete) 文を使って要素を削除す
      ることができます。

      Python に最初から組み込まれている変更可能なシーケンス型は、今の
      ところ二つです:

      リスト型 (list)
         リストの要素は任意の Python オブジェクトにできます。リストは
         、角括弧の中にカンマで区切られた式を並べて作ります。 (長さが
         0 や 1 のシーケンスを作るために特殊な場合分けは必要ないことに
         注意してください。)

      バイト配列
         bytearray オブジェクトは変更可能な配列です。組み込みの
         "bytearray()" コンストラクタによって作成されます。変更可能な
         ことを除けば (つまりハッシュ化できない)、 byte array は変更不
         能な bytes オブジェクトと同じインターフェースと機能を提供しま
         す。

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

集合型
   集合型は、順序のない、ユニークで不変なオブジェクトの有限集合を表現
   します。そのため、(配列の)添字を使ったインデックスアクセスはできま
   せん。ただし、イテレートは可能で、組み込み関数 "len()" は集合の要素
   数を返します。集合型の一般的な使い方は、集合に属しているかの高速な
   テスト、シーケンスからの重複の排除、共通集合・和集合・差・対称差と
   いった数学的な演算の計算です。

   集合の要素には、辞書のキーと同じ普遍性に関するルールが適用されます
   。数値型は通常の数値比較のルールに従うことに注意してください。もし2
   つの数値の比較結果が同値である(例えば、 "1" と "1.0")なら、そのうち
   の1つのみを集合に含めることができます。

   現在、2つの組み込み集合型があります:

   集合型
      可変な集合型です。組み込みの "set()" コンストラクタで作成され、
      後から "add()" などのいくつかのメソッドで更新できます。

   Frozen set 型
      不変な集合型です。組み込みの "frozenset()" コンストラクタによっ
      て作成されます。 frozenset は不変でハッシュ可能(*hashable*)なの
      で、別の集合型の要素になったり、辞書のキーにすることができます。

マッピング型 (mapping)
   任意のインデクス集合でインデクス化された、オブジェクトからなる有限
   の集合を表現します。添字表記 "a[k]" は、 "k" でインデクス指定された
   要素を "a" から選択します; 選択された要素は式の中で使うことができ、
   代入や "del" 文の対象にすることができます。組み込み関数 "len()" は
   、マッピング内の要素数を返します。

   Python に最初から組み込まれているマッピング型は、今のところ一つだけ
   です:

   辞書型 (dictionary)
      ほぼ任意の値でインデクスされたオブジェクトからなる有限の集合を表
      します。 キー (key) として使えない値の唯一の型は、リストや辞書、
      そしてオブジェクトの同一性でなく値で比較されるその他の変更可能な
      型です。 これは、辞書型を効率的に実装する上で、キーのハッシュ値
      が不変である必要があるためです。 数値型をキーに使う場合、キー値
      は通常の数値比較における規則に従います: 二つの値が等しくなる場合
      (例えば "1" と "1.0")、互いに同じ辞書のエントリを表すインデクス
      として使うことができます。

      辞書は変更可能な型です; 辞書は "{...}" 表記で生成します (辞書表
      現 を参照してください)。

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

呼び出し可能型 (callable type)
   関数呼び出し操作 (呼び出し (call) 参照) を行うことができる型です:

   ユーザ定義関数 (user-defined function)
      ユーザ定義関数オブジェクトは、関数定義を行うことで生成されます (
      関数定義 参照)。関数は、仮引数 (formal parameter) リストと同じ数
      の要素が入った引数リストとともに呼び出されます。

      特殊属性:

      +-------------------------+---------------------------------+-------------+
      | 属性                    | 意味                            |             |
      +=========================+=================================+=============+
      | "__doc__" "func_doc"    | The function’s documentation    | 書き込み可  |
      |                         | string, or "None" if            | 能          |
      |                         | unavailable.                    |             |
      +-------------------------+---------------------------------+-------------+
      | "__name__" "func_name"  | 関数の名前です                  | 書き込み可  |
      |                         |                                 | 能          |
      +-------------------------+---------------------------------+-------------+
      | "__module__"            | 関数が定義されているモジュール  | 書き込み可  |
      |                         | の名前です。モジュール名がない  | 能          |
      |                         | 場合 は "None" になります。     |             |
      +-------------------------+---------------------------------+-------------+
      | "__defaults__"          | A tuple containing default      | 書き込み可  |
      | "func_defaults"         | argument values for those       | 能          |
      |                         | arguments that have defaults,   |             |
      |                         | or "None" if no arguments have  |             |
      |                         | a default value.                |             |
      +-------------------------+---------------------------------+-------------+
      | "__code__" "func_code"  | コンパイルされた関数本体を表現  | 書き込み可  |
      |                         | するコードオブジェクトです。    | 能          |
      +-------------------------+---------------------------------+-------------+
      | "__globals__"           | 関数のグローバル変数の入った辞  | 読み込み専  |
      | "func_globals"          | 書 (への参照) です — この辞書は | 用          |
      |                         | 、 関数が定義されているモジュー |             |
      |                         | ルのグローバルな名前空間を決定  |             |
      |                         | します 。                       |             |
      +-------------------------+---------------------------------+-------------+
      | "__dict__" "func_dict"  | 任意の関数属性をサポートするた  | 書き込み可  |
      |                         | めの名前空間が収められています  | 能          |
      |                         | 。                              |             |
      +-------------------------+---------------------------------+-------------+
      | "__closure__"           | "None" または関数の個々の自由変 | 読み込み専  |
      | "func_closure"          | 数 (引数以外の変数) に対して値  | 用          |
      |                         | を 結び付けているセル (cell) 群 |             |
      |                         | からなるタプルになります。      |             |
      +-------------------------+---------------------------------+-------------+

      「書き込み可能」とラベルされている属性のほとんどは、代入された値
      の型をチェックします。

      バージョン 2.4 で変更: "func_name" is now writable.

      バージョン 2.6 で変更: The double-underscore attributes
      "__closure__", "__code__", "__defaults__", and "__globals__"
      were introduced as aliases for the corresponding "func_*"
      attributes for forwards compatibility with Python 3.

      関数オブジェクトはまた、任意の属性を設定したり取得したりできます
      。この機能は、例えば関数にメタデータを付与したい場合などに使えま
      す。関数の get や set には、通常のドット表記を使います。 *現在の
      実装では、ユーザ定義の関数でのみ属性をサポートしているので注意し
      て下さい。組み込み関数の属性は将来サポートする予定です。*

      関数定義に関するその他の情報は、関数のコードオブジェクトから得ら
      れます; 後述の内部型 (internal type) に関する説明を参照してくだ
      さい。

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

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

      バージョン 2.2 で変更: "im_self" used to refer to the class that
      defined the method.

      バージョン 2.6 で変更: For Python 3 forward-compatibility,
      "im_func" is also available as "__func__", and "im_self" as
      "__self__".

      メソッドもまた、根底にある関数オブジェクトの任意の関数属性に (値
      の設定はできませんが) アクセスできます。

      User-defined method objects may be created when getting an
      attribute of a class (perhaps via an instance of that class), if
      that attribute is a user-defined function object, an unbound
      user-defined method object, or a class method object. When the
      attribute is a user-defined method object, a new method object
      is only created if the class from which it is being retrieved is
      the same as, or a derived class of, the class stored in the
      original method object; otherwise, the original method object is
      used as it is.

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

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

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

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

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

      When a user-defined method object is derived from a class method
      object, the 「class instance」 stored in "im_self" will actually
      be the class itself, so that calling either "x.f(1)" or "C.f(1)"
      is equivalent to calling "f(C,1)" where "f" is the underlying
      function.

      Note that the transformation from function object to (unbound or
      bound) method object happens each time the attribute is
      retrieved from the class or instance. In some cases, a fruitful
      optimization is to assign the attribute to a local variable and
      call that local variable. Also notice that this transformation
      only happens for user-defined functions; other callable objects
      (and all non-callable objects) are retrieved without
      transformation.  It is also important to note that user-defined
      functions which are attributes of a class instance are not
      converted to bound methods; this *only* happens when the
      function is an attribute of the class.

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

   組み込み関数 (built-in function)
      組み込み関数オブジェクトはC関数へのラッパーです。 組み込み関数の
      例は "len()" や "math.sin()" ("math" は標準の組み込みモジュール)
      です。 引数の数や型は C 関数で決定されています。 読み出し専用の
      特殊属性: "__doc__" は関数のドキュメンテーション文字列です。 ド
      キュメンテーションがない場合は "None" になります; "__name__" は
      関数の名前です; "__self__" は "None" に設定されています (組み込
      みメソッドの節も参照してください); "__module__" は、関数が定義さ
      れているモジュールの名前です。 モジュール名がない場合は "None"
      になります。

   組み込みメソッド (built-in method)
      実際には組み込み関数を別の形で隠蔽したもので、こちらの場合には C
      関数に渡される何らかのオブジェクトを非明示的な外部引数として持っ
      ています。組み込みメソッドの例は、 *alist* をリストオブジェクト
      としたときの "alist.append()" です。この場合には、読み出し専用の
      属性 "__self__" は *alist* で表されるオブジェクトになります。

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

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

   クラスインスタンス (class instance)
      Class instances are described below.  Class instances are
      callable only when the class has a "__call__()" method;
      "x(arguments)" is a shorthand for "x.__call__(arguments)".

モジュール (module)
   Modules are imported by the "import" statement (see section import
   文). A module object has a namespace implemented by a dictionary
   object (this is the dictionary referenced by the func_globals
   attribute of functions defined in the module).  Attribute
   references are translated to lookups in this dictionary, e.g.,
   "m.x" is equivalent to "m.__dict__["x"]". A module object does not
   contain the code object used to initialize the module (since it
   isn’t needed once the initialization is done).

   属性の代入を行うと、モジュールの名前空間辞書の内容を更新します。例
   えば、 "m.x = 1" は "m.__dict__["x"] = 1" と同じです。

   読み出し専用の特殊属性: "__dict__" はモジュールの名前空間で、辞書オ
   ブジェクトです。

   CPython がモジュール辞書を削除する方法により、モジュール辞書が生き
   た参照を持っていたとしてもその辞書はモジュールがスコープから外れた
   時に削除されます。これを避けるには、辞書をコピーするか、辞書を直接
   使っている間モジュールを保持してください。

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

クラス
   Both class types (new-style classes) and class objects (old-
   style/classic classes) are typically created by class definitions
   (see section クラス定義).  A class has a namespace implemented by a
   dictionary object. Class attribute references are translated to
   lookups in this dictionary, e.g., "C.x" is translated to
   "C.__dict__["x"]" (although for new-style classes in particular
   there are a number of hooks which allow for other means of locating
   attributes). When the attribute name is not found there, the
   attribute search continues in the base classes.  For old-style
   classes, the search is depth-first, left-to-right in the order of
   occurrence in the base class list. New-style classes use the more
   complex C3 method resolution order which behaves correctly even in
   the presence of 『diamond』 inheritance structures where there are
   multiple inheritance paths leading back to a common ancestor.
   Additional details on the C3 MRO used by new-style classes can be
   found in the documentation accompanying the 2.3 release at
   https://www.python.org/download/releases/2.3/mro/.

   When a class attribute reference (for class "C", say) would yield a
   user-defined function object or an unbound user-defined method
   object whose associated class is either "C" or one of its base
   classes, it is transformed into an unbound user-defined method
   object whose "im_class" attribute is "C". When it would yield a
   class method object, it is transformed into a bound user-defined
   method object whose "im_self" attribute is "C".  When it would
   yield a static method object, it is transformed into the object
   wrapped by the static method object. See section デスクリプタ
   (descriptor) の実装 for another way in which attributes retrieved
   from a class may differ from those actually contained in its
   "__dict__" (note that only new-style classes support descriptors).

   クラス属性を代入すると、そのクラスの辞書だけが更新され、基底クラス
   の辞書は更新しません。

   クラスオブジェクトを呼び出す (上記を参照) と、クラスインスタンスを
   生成します (下記を参照)。

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

クラスインスタンス (class 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 or an unbound user-defined method object whose
   associated class is the class (call it "C") of the instance for
   which the attribute reference was initiated or one of its bases, it
   is transformed into a bound user-defined method object whose
   "im_class" attribute is "C" and whose "im_self" attribute is the
   instance. Static method and class method objects are also
   transformed, as if they had been retrieved from class "C"; see
   above under 「Classes」. See section デスクリプタ (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__()" メソッドが定義されている場合、直接インスタンスの辞
   書を更新する代わりにこれらのメソッドが呼び出されます。

   クラスインスタンスは、ある特定の名前のメソッドを持っている場合、数
   値型やシーケンス型、あるいはマップ型のように振舞うことができます。
   特殊メソッド名 を参照してください。

   特殊属性: "__dict__" は属性の辞書です; "__class__" はインスタンスの
   クラスです。

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

内部型 (internal type)
   インタプリタが内部的に使っているいくつかの型は、ユーザに公開されて
   います。これらの定義は将来のインタプリタのバージョンでは変更される
   可能性がありますが、ここでは記述の完全性のために触れておきます。

   コードオブジェクト
      コードオブジェクトは *バイトコンパイルされた (byte-compiled)* 実
      行可能な Python コード、別名バイトコード(*bytecode*) を表現しま
      す。コードオブジェクトと関数オブジェクトの違いは、関数オブジェク
      トが関数のグローバル変数 (関数を定義しているモジュールのグローバ
      ル) に対して明示的な参照を持っているのに対し、コードオブジェクト
      にはコンテキストがないということです; また、関数オブジェクトでは
      デフォルト引数値を記憶できますが、コードオブジェクトではできませ
      ん (実行時に計算される値を表現するため)。関数オブジェクトと違い
      、コードオブジェクトは変更不可能で、変更可能なオブジェクトへの参
      照を (直接、間接に関わらず) 含みません。

      読み出し専用の特殊属性: "co_name" は関数名を表します;
      "co_argcount" は固定引数 (positional argument) の数です;
      "co_nlocals" は関数が使う (引数を含めた) ローカル変数の数です;
      "co_varnames" はローカル変数名の入ったタプルです (引数名から始ま
      っています); "co_cellvars" はネストされた関数で参照されているロ
      ーカル変数の名前が入ったタプルです; "co_freevars" は自由変数の名
      前が入ったタプルです。 "co_code" はバイトコード列を表現している
      文字列です; "co_consts" はバイトコードで使われているリテラルの入
      ったタプルです; "co_names" はバイトコードで使われている名前の入
      ったタプルです; "co_filename" はバイトコードのコンパイルが行われ
      たファイル名です; "co_firstlineno" は関数の最初の行番号です;
      "co_lnotab" はバイトコードオフセットから行番号への対応付けをコー
      ド化した文字列です (詳細についてはインタプリタのソースコードを参
      照してください); "co_stacksize" は関数で (ローカル変数の分も含め
      て) 必要なスタックサイズです; "co_flags" はインタプリタ用の様々
      なフラグをコード化した整数です。

      以下のフラグビットが "co_flags" で定義されています: "0x04" ビッ
      トは、関数が "*arguments" 構文を使って任意の数の固定引数を受理で
      きる場合に立てられます; "0x08" ビットは、関数が "**keywords" 構
      文を使ってキーワード引数を受理できる場合に立てられます; "0x20"
      ビットは、関数がジェネレータである場合に立てられます。

      将来機能 (future feature) 宣言 ("from __future__ import
      division") もまた、 "co_flags" のビットを立てることで、コードオ
      ブジェクトが特定の機能を有効にしてコンパイルされていることを示し
      ます: "0x2000" ビットは、関数が将来機能を有効にしてコンパイルさ
      れている場合に立てられます; 以前のバージョンの Python では、
      "0x10" および "0x1000" ビットが使われていました。

      "co_flags" のその他のビットは将来に内部的に利用するために予約さ
      れています。

      コードオブジェクトが関数を表現している場合、 "co_consts" の最初
      の要素は関数のドキュメンテーション文字列になります。ドキュメンテ
      ーション文字列が定義されていない場合には "None" になります。

   フレーム (frame) オブジェクト
      フレームオブジェクトは実行フレーム (execution frame) を表します
      。実行フレームはトレースバックオブジェクト内に出現します (下記参
      照)。

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

      Special writable attributes: "f_trace", if not "None", is a
      function called at the start of each source code line (this is
      used by the debugger); "f_exc_type", "f_exc_value",
      "f_exc_traceback" represent the last exception raised in the
      parent frame provided another exception was ever raised in the
      current frame (in all other cases they are "None"); "f_lineno"
      is the current line number of the frame — writing to this from
      within a trace function jumps to the given line (only for the
      bottom-most frame).  A debugger can implement a Jump command
      (aka Set Next Statement) by writing to f_lineno.

   トレースバック (traceback) オブジェクト
      Traceback objects represent a stack trace of an exception.  A
      traceback object is created when an exception occurs.  When the
      search for an exception handler unwinds the execution stack, at
      each unwound level a traceback object is inserted in front of
      the current traceback.  When an exception handler is entered,
      the stack trace is made available to the program. (See section
      try 文.) It is accessible as "sys.exc_traceback", and also as
      the third item of the tuple returned by "sys.exc_info()".  The
      latter is the preferred interface, since it works correctly when
      the program is using multiple threads. When the program contains
      no suitable handler, the stack trace is written (nicely
      formatted) to the standard error stream; if the interpreter is
      interactive, it is also made available to the user as
      "sys.last_traceback".

      読み出し専用の特殊属性: "tb_next" はスタックトレース内の (例外の
      発生しているフレームに向かって) 次のレベルです。次のレベルが存在
      しない場合には "None" になります; "tb_frame" は現在のレベルにお
      ける実行フレームを指します; "tb_lineno" は例外の発生した行番号で
      す; "tb_lasti" は厳密な命令コードです。トレースバック内の行番号
      や最後に実行された命令は、 "try" 文内で例外が発生し、かつ対応す
      る "except" 節や "finally" 節がない場合には、フレームオブジェク
      ト内の行番号とは異なるかもしれません。

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

      読み込み専用の特殊属性: "start" は下限です; "stop" は上限です;
      "step" はステップの値です; それぞれ省略された場合は "None" とな
      っています。これらの属性は任意の型を持てます。

      スライスオブジェクトはメソッドを一つサポートします:

      slice.indices(self, length)

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

         バージョン 2.3 で追加.

   静的メソッド (static method) オブジェクト
      静的メソッドは、上で説明したような関数オブジェクトからメソッドオ
      ブジェクトへの変換を阻止するための方法を提供します。静的メソッド
      オブジェクトは他の何らかのオブジェクト、通常はユーザ定義メソッド
      オブジェクトを包むラッパです。静的メソッドをクラスやクラスインス
      タンスから取得すると、実際に返されるオブジェクトはラップされたオ
      ブジェクトになり、それ以上は変換の対象にはなりません。静的メソッ
      ドオブジェクトは通常呼び出し可能なオブジェクトをラップしますが、
      静的オブジェクト自体は呼び出すことができません。静的オブジェクト
      は組み込みコンストラクタ "staticmethod()" で生成されます。

   クラスメソッドオブジェクト
      クラスメソッドオブジェクトは、静的メソッドオブジェクトに似て、別
      のオブジェクトを包むラッパであり、そのオブジェクトをクラスやクラ
      スインスタンスから取り出す方法を代替します。このようにして取得し
      たクラスメソッドオブジェクトの動作については、上の 「ユーザ定義
      メソッド (user-defined method)」 で説明されています。クラスメソ
      ッドオブジェクトは組み込みのコンストラクタ "classmethod()" で生
      成されます。


New-style and classic classes
=============================

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

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

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

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

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

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

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


特殊メソッド名
==============

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

組み込み型をエミュレートするクラスを実装するときは、模範とされるオブジ
ェクトにとって意味がある範囲に実装をとどめるのが重要です。例えば、ある
シーケンスは個々の要素の取得はきちんと動くかもしれませんが、スライスの
展開が意味を為さないかもしれません。 (W3C のドキュメントオブジェクトモ
デルにある "NodeList" インターフェースがその一例です。)


基本的なカスタマイズ
--------------------

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

   クラス *cls* の新しいインスタンスを作るために呼び出されます。
   "__new__()" は静的メソッドで (このメソッドは特別扱いされているので
   、明示的に静的メソッドと宣言する必要はありません)、インスタンスを生
   成するよう要求されているクラスを第一引数にとります。残りの引数はオ
   ブジェクトのコンストラクタの式 (クラスの呼び出し文) に渡されます。
   "__new__()" の戻り値は新しいオブジェクトのインスタンス (通常は
   *cls* のインスタンス) でなければなりません。

   典型的な実装では、クラスの新たなインスタンスを生成するときには
   "super(currentclass, cls).__new__(cls[, ...])" に適切な引数を指定し
   てスーパクラスの "__new__()" メソッドを呼び出し、新たに生成されたイ
   ンスタンスに必要な変更を加えてから返します。

   "__new__()" が *cls* のインスタンスを返した場合、 "__init__(self[,
   ...])" のようにしてインスタンスの "__init__()" が呼び出されます。こ
   のとき、 *self* は新たに生成されたインスタンスで、残りの引数は
   "__new__()" に渡された引数と同じになります。

   "__new__()" が *cls* のインスタンスを返さない場合、インスタンスの
   "__init__()" メソッドは呼び出されません。

   "__new__()" の主な目的は、変更不能な型 (int, str, tuple など) のサ
   ブクラスでインスタンス生成をカスタマイズすることにあります。また、
   クラス生成をカスタマイズするために、カスタムのメタクラスでよくオー
   バーライドされます。

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

   インスタンスが ("__new__()" によって) 生成された後、それが呼び出し
   元に返される前に呼び出されます。引数はクラスのコンストラクタ式に渡
   したものです。基底クラスとその派生クラスがともに "__init__()" メソ
   ッドを持つ場合、派生クラスの "__init__()" メソッドは基底クラスの
   "__init__()" メソッドを明示的に呼び出して、インスタンスの基底クラス
   部分が適切に初期化されること保証しなければなりません。例えば、
   "BaseClass.__init__(self, [args...])" 。

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

object.__del__(self)

   インスタンスが消滅させられる際に呼び出されます。このメソッドはデス
   トラクタ (destructor)  とも呼ばれます。基底クラスとその派生クラスが
   ともに "__del__()" メソッドを持つ場合、派生クラスの "__del__()" メ
   ソッドは基底クラスの "__del__()" メソッドを明示的に呼び出して、イン
   スタンスの基底クラス部分が適切に消滅処理されること保証しなければな
   りません。 "__del__()" メソッドでインスタンスに対する新たな参照を作
   ることで、インスタンスの消滅を遅らせることができます (とはいえ、推
   奨しません！)。このようにすると、新たに作成された参照がその後削除さ
   れた際にもう一度 "__del__()" メソッドが呼び出されます。インタプリタ
   が終了する際に残っているオブジェクトに対して、 "__del__()" メソッド
   が呼び出される保証はありません。

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

   警告: "__del__()" メソッドの呼び出しが起きるのは不安定な状況下な
     ので、 "__del__()" の実行中に発生した例外は無視され、代わりに
     "sys.stderr" に警告が出力されます。また、 (例えばプログラムの実行
     終了による) モジュールの削除に伴って "__del__()" が呼び出される際
     には、 "__del__()" メソッドが参照している他のグローバル変数はすで
     に削除されていたり、削除中(例えば、import機構のシャットダウン中)
     かもしれません。この理由から、 "__del__()" メソッドでは外部の不変
     関係を維持する上で絶対最低限必要なことだけをすべきです。バージョ
     ン 1.5 からは、単一のアンダースコアで始まるようなグローバル変数は
     、他のグローバル変数が削除される前にモジュールから削除されるよう
     に Python 側で保証しています; これらのアンダースコア付きグローバ
     ル変数は、 "__del__()" が呼び出された際に、import されたモジュー
     ルがまだ残っているか確認する上で役に立ちます。

   See also the "-R" command-line option.

object.__repr__(self)

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

   この関数はデバッグの際によく用いられるので、たくさんの情報を含み、
   あいまいでないような表記にすることが重要です。

object.__str__(self)

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

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

   バージョン 2.1 で追加.

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

   拡張比較メソッドは与えられた引数のペアに対する演算を実装していない
   ときに、 シングルトン "NotImplemented" を返すかもしれません。 慣例
   として、正常に比較が行われたときには "False" か "True" を返します。
   しかし、これらのメソッドは任意の値を返すことができるので、比較演算
   子がブール値のコンテキスト (たとえば "if" 文の条件部分) で使われた
   場合、 Python はその値に対して "bool()" を呼び出して結果の真偽を判
   断します。

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

   There are no swapped-argument versions of these methods (to be used
   when the left argument does not support the operation but the right
   argument does); rather, "__lt__()" and "__gt__()" are each other’s
   reflection, "__le__()" and "__ge__()" are each other’s reflection,
   and "__eq__()" and "__ne__()" are their own reflection.

   Arguments to rich comparison methods are never coerced.

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

object.__cmp__(self, other)

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

object.__rcmp__(self, other)

   バージョン 2.1 で変更: No longer supported.

object.__hash__(self)

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

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

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

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

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

   バージョン 2.5 で変更: "__hash__()" may now also return a long
   integer object; the 32-bit integer is then derived from the hash of
   that object.

   バージョン 2.6 で変更: "__hash__" may now be set to "None" to
   explicitly flag instances of a class as unhashable.

object.__nonzero__(self)

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

object.__unicode__(self)

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


属性値アクセスをカスタマイズする
--------------------------------

以下のメソッドを定義して、クラスインスタンスへの属性値アクセス ( 属性
値の使用、属性値への代入、 "x.name" の削除) の意味をカスタマイズするこ
とができます。

object.__getattr__(self, name)

   属性値の検索を行った結果、通常の場所に属性値が見つからなかった場合
   (すなわち、 "self" のインスタンス属性でなく、かつクラスツリーにも見
   つからなかった場合) に呼び出されます。"name" は属性名です。このメソ
   ッドは (計算された) 属性値を返すか、 "AttributeError" 例外を送出し
   なければなりません。

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

object.__setattr__(self, name, value)

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

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

object.__delattr__(self, name)

   "__setattr__()" に似ていますが、代入ではなく値の削除を行います。こ
   のメソッドを実装するのは、オブジェクトにとって "del obj.name" が意
   味がある場合だけにしなければなりません。


More attribute access for new-style classes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The following methods only apply to new-style classes.

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


デスクリプタ (descriptor) の実装
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

以下のメソッドは、このメソッドを持つクラス (いわゆる *デスクリプタ
(descriptor)* クラス) のインスタンスが、 *オーナー (owner)* クラスに存
在するときにのみ適用されます (デスクリプタは、オーナーのクラス辞書か、
その親のいずれかのクラス辞書になければなりません)。 以下の例では、」属
性」 とは、名前がオーナークラスの "__dict__" のプロパティ (porperty)
のキーであるような属性を指します。

object.__get__(self, instance, owner)

   オーナクラスの属性を取得する (クラス属性へのアクセス) 際や、オーナ
   クラスのインスタンスの属性を取得する (インスタンス属性へのアクセス)
   場合に呼び出されます。 *owner* は常にオーナクラスです。一方、
   *instance* は属性へのアクセスを仲介するインスタンスか属性が *owner*
   を介してアクセスされる場合は "None" になります。このメソッドは (計
   算された) 属性値を返すか、 "AttributeError" 例外を送出しなければな
   りません。

object.__set__(self, instance, value)

   オーナクラスのインスタンス *instance* 上の属性を新たな値 *value* に
   設定する際に呼び出されます。

object.__delete__(self, instance)

   オーナクラスのインスタンス *instance* 上の属性を削除する際に呼び出
   されます。


デスクリプタの呼び出し
~~~~~~~~~~~~~~~~~~~~~~

一般にデスクリプタとは、特殊な 「束縛に関する動作 (binding behaviour)
」 をもつオブジェクト属性のことです。デスクリプタは、デスクリプタプロ
トコル (descriptor protocol) のメソッド: "__get__()", "__set__()", お
よび "__delete__()" を使って、属性アクセスをオーバライドしているもので
す。これらのメソッドのいずれかがオブジェクトに対して定義されている場合
、オブジェクトはデスクリプタであるといいます。

属性アクセスのデフォルトの動作は、オブジェクトの辞書から値を取り出した
り、値を設定したり、削除したりするというものです。例えば、 "a.x" によ
る属性の検索では、まず "a.__dict__['x']" 、次に
"type(a).__dict__['x']" 、そして "type(a)" の基底クラスでメタクラスで
ないものに続く、といった具合に連鎖が起こります。

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

デスクリプタ呼び出しの基点となるのは、属性名への束縛 (binding) 、すな
わち "a.x" です。引数がどのようにデスクリプタに結合されるかは "a" に依
存します:

直接呼び出し (Direct Call)
   最も単純で、かつめったに使われない呼び出し操作は、コード中で直接デ
   スクリプタメソッドの呼び出し: "x.__get__(a)" を行うというものです。

インスタンス束縛 (Instance Binding)
   If binding to a new-style object instance, "a.x" is transformed
   into the call: "type(a).__dict__['x'].__get__(a, type(a))".

クラス束縛 (Class Binding)
   If binding to a new-style class, "A.x" is transformed into the
   call: "A.__dict__['x'].__get__(None, A)".

super 束縛 (Super Binding)
   "a" が "super" のインスタンスである場合、束縛 "super(B, obj).m()"
   を行うとまず "A" 、続いて "B" に対して "obj.__class_.__mro__" を検
   索し、次に呼び出し: "A.__dict__['m'].__get__(obj, obj.__class__)"
   でデスクリプタを呼び出します。

インスタンス束縛では、デスクリプタ呼び出しの優先順位はどのデスクリプタ
が定義されているかに依存します。データデスクリプタは、 "__get__()" と
"__set__()" 、 "__delete__()" の任意の組合せを定義することができます。
"__get__()" が定義されない場合には、その属性にアクセスすると、そのオブ
ジェクトのインスタンス辞書にその値がある場合を除けば、デスクリプタオブ
ジェクト自身が返ってきます。デスクリプタが "__set__()" と
"__delete__()" またはそのどちらかを定義していれば、データデスクリプタ
となります; もし両方とも定義しなければ、非データデスクリプタです。通常
、データデスクリプタでは、 "__get__()" と "__set__()" を定義し、一方、
非データデスクリプタには "__get__()" メソッドしかありません。
"__set__()" と "__get__()" を定義したデータデスクリプタは、インスタン
ス辞書内で属性値が再定義されても、常にこの値をオーバライドします。対照
的に、非データデスクリプタの場合には、属性値はインスタンス側でオーバラ
イドされます。

("staticmethod()" や "classmethod()" を含む) Python メソッドは、非デー
タデスクリプタとして実装されています。その結果、インスタンスではメソッ
ドを再定義したりオーバライドできます。このことにより、個々のインスタン
スが同じクラスの他のインスタンスと互いに異なる動作を獲得することができ
ます。

"property()" 関数はデータデスクリプタとして実装されています。従って、
インスタンスはあるプロパティの動作をオーバライドすることができません。


__slots__
~~~~~~~~~

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

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

__slots__

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

   バージョン 2.2 で追加.

*__slots__* を利用する際の注意

* *__slots__* を持たないクラスから継承する場合、 *__dict__* 属性は常
  に アクセス可能なので、サブクラスで *__slots__* を定義しても意味があ
  り ません。

* *__dict__* 変数がない場合、 *__slots__* に列挙されていない新たな変
  数 をインスタンスに代入することはできません。列挙されていない変数名
  を使 って代入しようとした場合、 "AttributeError" が送出されます。新
  たな変 数を動的に代入したいのなら、 *__slots__* を宣言する際に
  "'__dict__'" を変数名のシーケンスに追加してください。

  バージョン 2.3 で変更: Previously, adding "'__dict__'" to the
  *__slots__* declaration would not enable the assignment of new
  attributes not specifically listed in the sequence of instance
  variable names.

* *__slots__* を定義しているクラスの各インスタンスに *__weakref__*
  変 数がない場合、インスタンスに対する弱参照 (weak reference) はサポ
  ート されません。弱参照のサポートが必要なら、 *__slots__* を宣言する
  際に "'__weakref__'" を変数名のシーケンスに追加してください。

  バージョン 2.3 で変更: Previously, adding "'__weakref__'" to the
  *__slots__* declaration would not enable support for weak
  references.

* *__slots__* は、クラスのレベルで各変数に対するデスクリプタ (デスク
  リ プタ (descriptor) の実装 を参照) を使って実装されます。その結果、
  *__slots__* に定義されているインスタンス変数のデフォルト値はクラス属
  性を使って設定できなくなっています; そうしないと、デスクリプタによる
  代入をクラス属性が上書きしてしまうからです。

* *__slots__* 宣言が動作するのは、定義が行われたクラスだけに限られて
  い ます。その結果、サブクラスでは、 *__slots__* を定義しない限り
  *__dict__* を持つことになります。

* あるクラスで、基底クラスですでに定義されているスロットを定義した場
  合 、基底クラスのスロットで定義されているインスタンス変数は (デスク
  リプ タを基底クラスから直接取得しない限り) アクセスできなくなります
  。これ により、プログラムの趣意が不定になってしまいます。将来は、こ
  の問題を 避けるために何らかのチェックが追加されるかもしれません。

* Nonempty *__slots__* does not work for classes derived from 「
  variable-length」 built-in types such as "long", "str" and "tuple".

* *__slots__* には、文字列でない反復可能オブジェクトを代入することが
  で きます。辞書型も使うことができます; しかし将来、辞書の各キーに相
  当す る値に何らかの特殊な意味が割り当てられるかもしれません。

* *__class__* への代入は、両方のクラスが同じ *__slots__* を持ってい
  る ときのみ動作します。

  バージョン 2.6 で変更: Previously, *__class__* assignment raised an
  error if either new or old class had *__slots__*.


クラス生成をカスタマイズする
----------------------------

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

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

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

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

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

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

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

__metaclass__

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

   バージョン 2.2 で追加.

The appropriate metaclass is determined by the following precedence
rules:

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

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

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

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

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


インスタンスのカスタマイズとサブクラスチェック
----------------------------------------------

バージョン 2.6 で追加.

以下のメソッドは組み込み関数 "isinstance()" と "issubclass()" のデフォ
ルトの動作を上書きするのに利用します。

特に、 "abc.ABCMeta" メタクラスは、抽象基底クラス (ABCs) を」仮想基底
クラス (virtual base classes)」 として、他の ABC を含む、任意のクラス
や (組み込み型を含む) 型に追加するために、これらのメソッドを実装してい
ます。

class.__instancecheck__(self, instance)

   *instance* が (直接、または間接的に) *class* のインスタンスと考えら
   れる場合に true を返します。定義されていれば、
   "isinstance(instance, class)" の実装のために呼び出されます。

class.__subclasscheck__(self, subclass)

   *subclass* が (直接、または間接的に) *class* のサブクラスと考えられ
   る場合に true を返します。定義されていれば、 "issubclass(subclass,
   class)" の実装のために呼び出されます。

なお、これらのメソッドは、クラスの型 (メタクラス) 上で検索されます。実
際のクラスにクラスメソッドとして定義することはできません。これは、イン
スタンスそれ自体がクラスであるこの場合にのみ、インスタンスに呼び出され
る特殊メソッドの検索と一貫しています。

参考:

  **PEP 3119** - 抽象基底クラスの導入
     抽象基底クラス ("abc" モジュールを参照) を言語に追加する文脈にお
     いての動機から、 "__instancecheck__()" と "__subclasscheck__()"
     を通して、 "isinstance()" と "issubclass()" に独自の動作をさせる
     ための仕様の記述があります。


呼び出し可能オブジェクトをエミュレートする
------------------------------------------

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

   インスタンスが関数として 「呼ばれた」 際に呼び出されます; このメソ
   ッドが定義されている場合、 "x(arg1, arg2, ...)" は
   "x.__call__(arg1, arg2, ...)" を短く書いたものになります。


コンテナをエミュレートする
--------------------------

The following methods can be defined to implement container objects.
Containers usually are sequences (such as lists or tuples) or mappings
(like dictionaries), but can represent other containers as well.  The
first set of methods is used either to emulate a sequence or to
emulate a mapping; the difference is that for a sequence, the
allowable keys should be the integers *k* for which "0 <= k < N" where
*N* is the length of the sequence, or slice objects, which define a
range of items. (For backwards compatibility, the method
"__getslice__()" (see below) can also be defined to handle simple, but
not extended slices.) It is also recommended that mappings provide the
methods "keys()", "values()", "items()", "has_key()", "get()",
"clear()", "setdefault()", "iterkeys()", "itervalues()",
"iteritems()", "pop()", "popitem()", "copy()", and "update()" behaving
similar to those for Python’s standard dictionary objects.  The
"UserDict" module provides a "DictMixin" class to help create those
methods from a base set of "__getitem__()", "__setitem__()",
"__delitem__()", and "keys()". Mutable sequences should provide
methods "append()", "count()", "index()", "extend()", "insert()",
"pop()", "remove()", "reverse()" and "sort()", like Python standard
list objects.  Finally, sequence types should implement addition
(meaning concatenation) and multiplication (meaning repetition) by
defining the methods "__add__()", "__radd__()", "__iadd__()",
"__mul__()", "__rmul__()" and "__imul__()" described below; they
should not define "__coerce__()" or other numerical operators.  It is
recommended that both mappings and sequences implement the
"__contains__()" method to allow efficient use of the "in" operator;
for mappings, "in" should be equivalent of "has_key()"; for sequences,
it should search through the values.  It is further recommended that
both mappings and sequences implement the "__iter__()" method to allow
efficient iteration through the container; for mappings, "__iter__()"
should be the same as "iterkeys()"; for sequences, it should iterate
through the values.

object.__len__(self)

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

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

object.__getitem__(self, key)

   "self[key]" の値評価 (evaluation) を実現するために呼び出されます。
   シーケンスの場合、キーとして整数とスライスオブジェクトを受理できな
   ければなりません。 (シーケンス型をエミュレートする場合) 負のインデ
   クスの解釈は "__getitem__()" メソッド次第となります。 *key* が不適
   切な型であった場合、 "TypeError" を送出してもかまいません; (負のイ
   ンデクス値に対して何らかの解釈を行った上で) *key* がシーケンスのイ
   ンデクス集合外の値である場合、 "IndexError" を送出しなければなりま
   せん。マップ型の場合は、 *key* に誤りがある場合（コンテナに含まれて
   いない場合）、 "KeyError" を送出しなければなりません。

   注釈: "for" ループでは、シーケンスの終端を正しく検出できるように
     するた めに、不正なインデクスに対して "IndexError" が送出されるも
     のと期 待しています。

object.__missing__(self, key)

   "self[key]" の実装において辞書内にキーが存在しなかった場合に、 dict
   のサブクラスのために "dict"."__getitem__()" によって呼び出されます
   。

object.__setitem__(self, key, value)

   "self[key]" に対する代入を実装するために呼び出されます。
   "__getitem__()" と同じ注意事項があてはまります。このメソッドを実装
   できるのは、あるキーに対する値の変更をサポートしているか、新たなキ
   ーを追加できるようなマップの場合と、ある要素を置き換えることができ
   るシーケンスの場合だけです。不正な *key* に対しては、
   "__getitem__()" メソッドと同様の例外の送出を行わなければなりません
   。

object.__delitem__(self, key)

   "self[key]" の削除を実装するために呼び出されます。 "__getitem__()"
   と同じ注意事項があてはまります。このメソッドを実装できるのは、キー
   の削除をサポートしているマップの場合と、要素を削除できるシーケンス
   の場合だけです。不正な *key* に対しては、 "__getitem__()" メソッド
   と同様の例外の送出を行わなければなりません。

object.__iter__(self)

   This method is called when an iterator is required for a container.
   This method should return a new iterator object that can iterate
   over all the objects in the container.  For mappings, it should
   iterate over the keys of the container, and should also be made
   available as the method "iterkeys()".

   イテレータオブジェクトでもこのメソッドを実装する必要があります; イ
   テレータの場合、自分自身を返さなければなりません。イテレータオブジ
   ェクトに関するより詳細な情報は、 イテレータ型 を参照してください。

object.__reversed__(self)

   "reversed()" 組み込み関数が逆方向イテレーションを実装するために、(
   存在すれば)呼び出します。コンテナ内の全要素を逆順にイテレートする、
   新しいイテレータを返すべきです。

   "__reversed__()" メソッドが定義されていない場合、 "reversed()" 組込
   み関数は sequence プロトコル ("__len__()" と "__getitem__()") を使
   った方法にフォールバックします。 sequence プロトコルをサポートした
   オブジェクトは、 "reversed()" よりも効率のいい実装を提供できる場合
   にのみ "__reversed__()" を定義するべきです。

   バージョン 2.6 で追加.

帰属テスト演算子 ("in" および "not in") は通常、シーケンスに渡る反復処
理を使って実装されます。しかし、コンテナオブジェクトで以下の特殊メソッ
ドを定義して、より効率的な実装を行ったり、オブジェクトがシーケンスでな
くてもよいようにできます。

object.__contains__(self, item)

   帰属テスト演算を実装するために呼び出されます。 *item* が *self* 内
   に存在する場合には真を、そうでない場合には偽を返さなければなりませ
   ん。マップオブジェクトの場合、値やキーと値の組ではなく、キーに対す
   る帰属テストを考えなければなりません。

   "__contains__()" を定義しないオブジェクトに対しては、メンバシップテ
   ストはまず、 "__iter__()" を使った反復を試みます、次に古いシーケン
   ス反復プロトコル "__getitem__()" を使います、 言語レファレンスのこ
   の節 を参照して下さい。


Additional methods for emulation of sequence types
--------------------------------------------------

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

object.__getslice__(self, i, j)

   バージョン 2.0 で撤廃: Support slice objects as parameters to the
   "__getitem__()" method. (However, built-in types in CPython
   currently still implement "__getslice__()".  Therefore, you have to
   override it in derived classes when implementing slicing.)

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

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

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

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

object.__delslice__(self, i, j)

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

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

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

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

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

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

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


数値型をエミュレーションする
----------------------------

以下のメソッドを定義して、数値型オブジェクトをエミュレートすることがで
きます。特定の種類の数値型ではサポートされていないような演算に対応する
メソッド (非整数の数値に対するビット単位演算など) は、未定義のままにし
ておかなければなりません。

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

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

   これらのメソッドのいずれかが渡された引数に対する操作を提供していな
   い場合、 "NotImplemented" を送出しなければなりません。

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

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

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

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

   ただし、三項演算子 "pow()" が "__rpow__()" を呼ぶことはないので注意
   してください (型強制の規則が非常に難解になるからです)。

   注釈: 右側の被演算子の型が左側の被演算子の型のサブクラスであり、
     このサ ブクラスであるメソッドに対する反射メソッドが定義されている
     場合に は、左側の被演算子の非反射メソッドが呼ばれる前に、このメソ
     ッドが 呼ばれます。この振る舞いにより、サブクラスが親の演算をオー
     バーラ イドすることが可能になります。

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

   These methods are called to implement the augmented arithmetic
   assignments ("+=", "-=", "*=", "/=", "//=", "%=", "**=", "<<=",
   ">>=", "&=", "^=", "|=").  These methods should attempt to do the
   operation in-place (modifying *self*) and return the result (which
   could be, but does not have to be, *self*).  If a specific method
   is not defined, the augmented assignment falls back to the normal
   methods.  For instance, to execute the statement "x += y", where
   *x* is an instance of a class that has an "__iadd__()" method,
   "x.__iadd__(y)" is called.  If *x* is an instance of a class that
   does not define a "__iadd__()" method, "x.__add__(y)" and
   "y.__radd__(x)" are considered, as with the evaluation of "x + y".

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

   呼び出して単項算術演算 ("-", "+", "abs()" および "~") を実装します
   。

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

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

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

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

object.__index__(self)

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

   バージョン 2.5 で追加.

object.__coerce__(self, other)

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


Coercion rules
--------------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  バージョン 2.7 で変更: The complex type no longer makes implicit
  calls to the "__coerce__()" method for mixed-type binary arithmetic
  operations.


with文とコンテキストマネージャ
------------------------------

バージョン 2.5 で追加.

コンテキストマネージャ(*context manager*) とは、 "with" 文の実行時にラ
ンタイムコンテキストを定義するオブジェクトです。コンテキストマネージャ
は、コードブロックを実行するために必要な入り口および出口の処理を扱いま
す。コンテキストマネージャは通常、 "with" 文（ with 文 の章を参照）に
より起動されますが、これらのメソッドを直接呼び出すことで起動することも
できます。

コンテキストマネージャの代表的な使い方としては、様々なグローバル情報の
保存および更新、リソースのロックとアンロック、ファイルのオープンとクロ
ーズなどが挙げられます。

コンテキストマネージャについてのさらなる情報については、 コンテキスト
マネージャ型 を参照してください。

object.__enter__(self)

   コンテキストマネージャのの入り口で実行される処理です。 "with" 文は
   、文の "as" 節で規定された値を返すこのメソッドを呼び出します。

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

   コンテキストマネージャの出口で実行される処理です。パラメータは、コ
   ンテキストが終了した原因となった例外について説明しています。コンテ
   キストが例外を送出せず終了した場合は、全ての引き数に "None" が設定
   されます。

   もし、例外が送出され、かつメソッドが例外を抑制したい場合（すなわち
   、例外が伝播されるのを防ぎたい場合）、このメソッドは True を返す必
   要があります。そうでなければ、このメソッドの終了後、例外は通常通り
   伝播することになります。

   "__exit__()" メソッドは受け取った例外を再度送出すべきではありません
   。これは、呼び出し側の責任でおこなってください。

参考:

  **PEP 343** - 「with」 ステートメント
     Python の "with" 文の仕様、背景、および例が記載されています。


Special method lookup for old-style classes
-------------------------------------------

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

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

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


Special method lookup for new-style classes
-------------------------------------------

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

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

この動作の背景となる理由は、 "__hash__()" と "__repr__()" といった
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__()" 機構をバイパスすることで、特殊メソッド
の扱いに関するある程度の自由度と引き換えに (特殊メソッドはインタプリタ
から一貫して実行されるためにクラスオブジェクトに設定 *しなければならな
い*)、インタープリタを高速化するための大きな余地が手に入ります。

-[ 脚注 ]-

[1] 特定の条件が満たされた場合、オブジェクトの type を変更すること
    が * できます* 。これは、正しく扱われなかった場合にとても奇妙な動
    作を引 き起こすので、一般的には良い考えではありません。

[2] 同じ型の被演算子については、無反転のメソッド (たとえば
    "__add__()") が失敗した場合、その演算はサポートされていないとみな
    されます。 これは、反射したメソッドが呼び出されないためです。
