pytho****@googl*****
pytho****@googl*****
2011年 3月 7日 (月) 16:56:28 JST
Revision: 7a15317f23 Author: INADA Naoki <inada****@klab*****> Date: Sun Mar 6 23:54:20 2011 Log: レビュー: tutorial/classes.rst (途中まで) http://code.google.com/p/python-doc-ja/source/detail?r=7a15317f23 Modified: /tutorial/classes.rst ======================================= --- /tutorial/classes.rst Thu Feb 10 04:41:15 2011 +++ /tutorial/classes.rst Sun Mar 6 23:54:20 2011 @@ -85,10 +85,13 @@ 変更不能な基本型 (数値、文字列、タプル)を扱うときには無視して差し支えありま せん。 しかしながら、別名付けは、リストや辞書や他の多くの型など、変更可能な型を扱 う Python コード上で驚くべき効果があります。 -別名付けはいくつかの点でポインタのように振舞い、このことは通常はプログラム に利するように使われます。 -例えば、オブジェクトの受け渡しは、実装上はポインタが渡されるだけなのでコス トの低い操作になります。 +別名付けはいくつかの点でポインタのように振舞い、このことは通常はプログラム に +利するように使われます。 +例えば、オブジェクトの受け渡しは、実装上はポインタが渡されるだけなのでコス トの +低い操作になります。 また、関数があるオブジェクトを引数として渡されたとき、関数の呼び出し側から -オブジェクトに対する変更を見ることができます --- これにより、 Pascal にある ような二つの引数渡し機構をもつ必要をなくしています。 +オブジェクトに対する変更を見ることができます --- これにより、 Pascal +にあるような二つの引数渡し機構をもつ必要をなくしています。 .. _tut-scopes: @@ -98,123 +101,68 @@ クラスを紹介する前に、Python のスコープのルールについてあることを 話しておかなければなりません。 -クラス定義はある巧みなトリックを名前空間に施すので、 +クラス定義は巧みなトリックを名前空間に施すので、 何が起こっているのかを完全に理解するには、スコープと名前空間が どのように動作するかを理解する必要があります。 ちなみに、この問題に関する知識は全ての Python プログラマにとって有用です。 -.. % Python Scopes and Name Spaces -.. % % Before introducing classes, I first have to tell you something about -.. % % Python's scope rules. Class definitions play some neat tricks with -.. % % namespaces, and you need to know how scopes and namespaces work to -.. % % fully understand what's going on. Incidentally, knowledge about this -.. % % subject is useful for any advanced Python programmer. - まず定義から始めましょう。 -.. % % Let's begin with some definitions. - *名前空間 (namespace)* とは、名前からオブジェクトへの対応付け (mapping) で す。 ほとんどの名前空間は、現状では Python の辞書として実装されていますが、 そのことは通常は (パフォーマンス以外では) 目立つことはないし、将来は変更さ れるかもしれません。 -名前空間の例には、組込み名の集合 (:func:`abs` 等の関数や組込み例外名)、モジ ュール内のグローバルな名前; -関数を呼び出したときのローカルな名前、があります。 +名前空間の例には、組込み名の集合 (:func:`abs` 等の関数や組込み例外名)、 +モジュール内のグローバルな名前、関数を呼び出したときのローカルな名前があり ます。 オブジェクトの属性からなる集合もまた、ある意味では名前空間です。 -名前空間について知っておくべき重要なことは、異なった名前空間にある名前の間 には全く関係がないということです; +名前空間について知っておくべき重要なことは、異なった名前空間にある名前の間 には +全く関係がないということです。 例えば、二つの別々のモジュールの両方で関数 ``maximize`` という関数を定義することができ、定義自体は混同されることはありません --- モジュールのユーザは名前の前にモジュール名をつけなければなりません。 -.. % % A \emph{namespace} is a mapping from names to objects. Most -.. % % namespaces are currently implemented as Python dictionaries, but -.. % % that's normally not noticeable in any way (except for performance), -.. % % and it may change in the future. Examples of namespaces are: the set -.. % % of built-in names (functions such as \function{abs()}, and built-in -.. % % exception names); the global names in a module; and the local names in -.. % % a function invocation. In a sense the set of attributes of an object -.. % % also form a namespace. The important thing to know about namespaces -.. % % is that there is absolutely no relation between names in different -.. % % namespaces; for instance, two different modules may both define a -.. % % function ``maximize'' without confusion --- users of the modules must -.. % % prefix it with the module name. - -ところで、 *属性* という言葉は、ドットに続く名前すべてに対して使っています --- 例えば式 ``z.real`` で、 ``real`` はオブジェクト -``z`` の属性です。厳密にいえば、モジュール内の名前に対する参照は属性の参照 です: 式 ``modname.funcname`` では、 -``modname`` はあるモジュールオブジェクトで、 ``funcname`` はその属性です。 この場合には、たまたまモジュールの属性とモジュール内の -グローバルな名前の間にはこの場合はたまたま、モジュールの属性とモジュールで 定義されているグローバル名の間には、直接的な対応付けがされます: これらの名前 は -同じ名前空間を共有しているのです! [#]_ - -.. % % By the way, I use the word \emph{attribute} for any name following a -.. % % dot --- for example, in the expression \code{z.real}, \code{real} is -.. % % an attribute of the object \code{z}. Strictly speaking, references to -.. % % names in modules are attribute references: in the expression -.. % % \code{modname.funcname}, \code{modname} is a module object and -.. % % \code{funcname} is an attribute of it. In this case there happens to -.. % % be a straightforward mapping between the module's attributes and the -.. % % global names defined in the module: they share the same namespace! -.. % % \footnote{ -.. % % Except for one thing. Module objects have a secret read-only -.. % % attribute called \member{__dict__} which returns the dictionary -.. % % used to implement the module's namespace; the name -.. % % \member{__dict__} is an attribute but not a global name. -.. % % Obviously, using this violates the abstraction of namespace -.. % % implementation, and should be restricted to things like -.. % % post-mortem debuggers. -.. % % } - -属性は読取り専用にも、書き込み専用にもできます。後者の場合、属性に代入する ことができます。モジュール属性は書込み可能です: -``modname.the_answer = 42`` と書くことができます。書込み可能な属性 は、 :keyword:`del` 文で削除することも -できます。例えば、 ``del modname.the_answer`` は、 ``modname`` で指定され たオブジェクトから属性 -:attr:`the_answer` を除去します。 - -.. % % Attributes may be read-only or writable. In the latter case, -.. % % assignment to attributes is possible. Module attributes are writable: -.. % % you can write \samp{modname.the_answer = 42}. Writable attributes may -.. % % also be deleted with the \keyword{del} statement. For example, -.. % % \samp{del modname.the_answer} will remove the attribute -.. % % \member{the_answer} from the object named by \code{modname}. - -名前空間は様々な時点で作成され、その寿命も様々です。組み込みの名前が入った 名前空間は Python インタプリタが起動するときに -作成され、決して削除されることはありません。モジュールのグローバルな名前空 間は、モジュール定義が読み込まれたときに作成されます; 通常、 -モジュールの名前空間は、インタプリタが終了するまで残ります。インタプリタの トップレベルで実行された文は、スクリプトファイルから -読み出されたものでも対話的に読み出されたものでも、 :mod:`__main__` という名 前のモジュールの一部分であるとみなされるので、独自の -名前空間を持つことになります。(組み込みの名前は実際にはモジュール内に存在し ます; そのモジュールは :mod:`__builtin__` -と呼ばれています。) - -.. % % Name spaces are created at different moments and have different -.. % % lifetimes. The namespace containing the built-in names is created -.. % % when the Python interpreter starts up, and is never deleted. The -.. % % global namespace for a module is created when the module definition -.. % % is read in; normally, module namespaces also last until the -.. % % interpreter quits. The statements executed by the top-level -.. % % invocation of the interpreter, either read from a script file or -.. % % interactively, are considered part of a module called -.. % % \module{__main__}, so they have their own global namespace. (The -.. % % built-in names actually also live in a module; this is called -.. % % \module{__builtin__}.) - -関数のローカルな名前空間は、関数が呼び出されたときに作成され、関数から戻っ たときや、関数内で例外が送出され、かつ関数内で処理されなかった場合に削除され ます。 -(実際には、忘れられる、と言ったほうが起きていることをよく表しています。) も ちろん、再帰呼出しのときには、各々の呼び出しで各自の -ローカルな名前空間があります。 - -.. % % The local namespace for a function is created when the function is -.. % % called, and deleted when the function returns or raises an exception -.. % % that is not handled within the function. (Actually, forgetting would -.. % % be a better way to describe what actually happens.) Of course, -.. % % recursive invocations each have their own local namespace. - -*スコープ (scope)* とは、ある名前空間が直接アクセスできる (directly accessible) ような、Python -プログラムのテキスト上の領域です。 "直接アクセス可能" とは、限定なし (unqualified) である名前を参照 -した際に、その名前空間から名前を見つけようと試みることを意味します。 - -.. % % A \emph{scope} is a textual region of a Python program where a -.. % % namespace is directly accessible. ``Directly accessible'' here means -.. % % that an unqualified reference to a name attempts to find the name in -.. % % the namespace. +ところで、 *属性* という言葉は、ドットに続く名前すべてに対して使っています --- +例えば式 ``z.real`` で、 ``real`` はオブジェクト ``z`` の属性です。 +厳密にいえば、モジュール内の名前に対する参照は属性の参照です。 +式 ``modname.funcname`` では、 ``modname`` はあるモジュールオブジェクトで、 +``funcname`` はその属性です。 +この場合には、モジュールの属性とモジュールの中で定義されている +グローバル名の間には、直接的な対応付けがされます。 +これらの名前は同じ名前空間を共有しているのです! [#]_ + +属性は読取り専用にも、書込み可能にもできます。 +書込み可能であれば、属性に代入することができます。モジュール属性は書込み可 能で、 +``modname.the_answer = 42`` と書くことができます。書込み可能な属性は、 +:keyword:`del` 文で削除することもできます。 +例えば、 ``del modname.the_answer`` は、 ``modname`` で指定された +オブジェクトから属性 :attr:`the_answer` を除去します。 + +名前空間は様々な時点で作成され、その寿命も様々です。 +組み込みの名前が入った名前空間は Python インタプリタが起動するときに作成さ れ、 +決して削除されることはありません。 +モジュールのグローバルな名前空間は、モジュール定義が読み込まれたときに +作成されます。 +通常、モジュールの名前空間は、インタプリタが終了するまで残ります。 +インタプリタのトップレベルで実行された文は、スクリプトファイルから +読み出されたものでも対話的に読み出されたものでも、 :mod:`__main__` という名 前の +モジュールの一部分であるとみなされるので、独自の名前空間を持つことになりま す。 +(組み込みの名前は実際にはモジュール内に存在します。そのモジュールは +:mod:`__builtin__` と呼ばれています。) + +関数のローカルな名前空間は、関数が呼び出されたときに作成され、関数から +戻ったときや、関数内で例外が送出され、かつ関数内で処理されなかった場合に +削除されます。 +(実際には、忘れられる、と言ったほうが起きていることをよく表しています。) +もちろん、再帰呼出しのときには、各々の呼び出しで各自のローカルな +名前空間があります。 + +*スコープ (scope)* とは、ある名前空間が直接アクセスできるような、 Python +プログラムのテキスト上の領域です。 +"直接アクセス可能" とは、修飾なしに (訳注: ``spam.egg`` ではなく単に ``egg`` +のように) 名前を参照した際に、その名前空間から名前を見つけようと試みること を意味します。 スコープは静的に決定されますが、動的に使用されます。 -実行中はいつでも、直接名前空間にアクセス可能な、少なくとも三つの入れ子にな ったスコープがあります: -最初に検索される最も内側のスコープには、ローカルな名前が入っています: +実行中はいつでも、直接名前空間にアクセス可能な、少なくとも三つの入れ子にな った +スコープがあります。 * 最初に探される、最も内側のスコープは、ローカルな名前を持っています。 * 外側の(enclosing)関数のスコープは、近いほうから順に探され、 @@ -222,90 +170,52 @@ * 次のスコープは、現在のモジュールのグローバルな名前を持っています。 * 一番外側の(最後に検索される)スコープはビルトイン名を持っています。 -.. % % Although scopes are determined statically, they are used dynamically. -.. % % At any time during execution, there are at least three nested scopes whose -.. % % namespaces are directly accessible: the innermost scope, which is searched -.. % % first, contains the local names; the namespaces of any enclosing -.. % % functions, which are searched starting with the nearest enclosing scope; -.. % % the middle scope, searched next, contains the current module's global names; -.. % % and the outermost scope (searched last) is the namespace containing built-in -.. % % names. - -名前がグローバルであると宣言されている場合、その名前に対する参照や代入は全 て、 +名前が global と宣言されている場合、その名前に対する参照や代入は全て、 モジュールのグローバルな名前の入った中間のスコープに対して直接行われます。 -そうでない場合、最も内側のスコープより外側にある変数は全て読み出し専用 -(そのような変数に対する書き込みは、単に *新しい* ローカル変数もっとも -内側のスコープで作成し、外部のスコープの値は変化しません)となります。 - -.. % % If a name is declared global, then all references and assignments go -.. % % directly to the middle scope containing the module's global names. -.. % % Otherwise, all variables found outside of the innermost scope are read-only -.. % % (an attempt to write to such a variable will simply create a \emph{new} -.. % % local variable in the innermost scope, leaving the identically named -.. % % outer variable unchanged). - -通常、ローカルスコープは (プログラムテキスト上の) 現在の関数のローカルな名 前を参照します。関数の外側では、ローカルスコープは -グローバルな名前空間と同じ名前空間: モジュールの名前空間を参照します。クラ スを定義すると、ローカルスコープの中にもう一つ名前空間が置かれます。 - -.. % % Usually, the local scope references the local names of the (textually) -.. % % current function. Outside functions, the local scope references -.. % % the same namespace as the global scope: the module's namespace. -.. % % Class definitions place yet another namespace in the local scope. - -スコープはテキスト上で決定されていると理解することが重要です: モジュール内 で定義される関数のグローバルなスコープは、 -関数がどこから呼び出されても、どんな別名をつけて呼び出されても、そのモジ ュールの名前空間になります。反対に、実際の名前の検索は実行時に動的に行われま す ---- とはいえ、言語の定義は、"コンパイル" 時の静的な名前解決の方向に進化し ているので、動的な名前解決に頼ってはいけません! +そうでない場合、最も内側のスコープより外側にある変数は全て読み出し専用と +なります。 +(そのような変数に対する書き込みは、単に *新しい* ローカル変数をもっとも +内側のスコープで作成し、外部のスコープの値は変化しません) + +通常、ローカルスコープは (プログラムテキスト上の) 現在の関数のローカルな名 前を +参照します。関数の外側では、ローカルスコープはグローバルな名前空間と同じ +名前空間、モジュールの名前空間を参照します。 +クラス定義では、ローカルスコープの中にもう一つ名前空間が置かれます。 + +スコープはテキスト上で決定されていると理解することが重要です。 +モジュール内で定義される関数のグローバルなスコープは、 +関数がどこから呼び出されても、どんな別名をつけて呼び出されても、 +そのモジュールの名前空間になります。 +反対に、実際の名前の検索は実行時に動的に行われます +--- とはいえ、言語の定義は、"コンパイル" 時の静的な名前解決の方向に +進化しているので、動的な名前解決に頼ってはいけません! (事実、ローカルな変数は既に静的に決定されています。) -.. % % It is important to realize that scopes are determined textually: the -.. % % global scope of a function defined in a module is that module's -.. % % namespace, no matter from where or by what alias the function is -.. % % called. On the other hand, the actual search for names is done -.. % % dynamically, at run time --- however, the language definition is -.. % % evolving towards static name resolution, at ``compile'' time, so don't -.. % % rely on dynamic name resolution! (In fact, local variables are -.. % % already determined statically.) - -Python 特有の癖として、代入を行うと -- どの :keyword:`global` 文も有効でな い場合は -- -名前がいつも最も内側のスコープに入るというものがあります。 -代入はデータのコピーを行いません --- 単に名前をオブジェクトに結びつける (bind) だけです。 -オブジェクトの削除でも同じです: ``del x`` は、 ``x`` -をローカルスコープが参照している名前空間から削除します。実際、新たな名前を 導入する操作は全てローカルスコープを用います: とりわけ、 import -文や関数定義は、モジュールや関数の名前をローカルスコープに結び付けます。 (:keyword:`global` 文を使えば、 -特定の変数がグローバルスコープにあることを示せます。) - -.. % % A special quirk of Python is that assignments always go into the -.. % % innermost scope. Assignments do not copy data --- they just -.. % % bind names to objects. The same is true for deletions: the statement -.. % % \samp{del x} removes the binding of \code{x} from the namespace -.. % % referenced by the local scope. In fact, all operations that introduce -.. % % new names use the local scope: in particular, import statements and -.. % % function definitions bind the module or function name in the local -.. % % scope. (The \keyword{global} statement can be used to indicate that -.. % % particular variables live in the global scope.) - +Python 特有の癖として、代入を行うと -- どの :keyword:`global` 文も有効でな い +場合は -- 名前がいつも最も内側のスコープに入るというものがあります。 +代入はデータのコピーを行いません --- 単に名前をオブジェクトに結びつける (bind) +だけです。 +オブジェクトの削除でも同じです: ``del x`` は、 ``x`` をローカルスコープが +参照している名前空間から削除します。 +実際、新たな名前を導入する操作は全てローカルスコープを用います。 +とりわけ、 import 文や関数定義は、モジュールや関数の名前をローカルスコープ に +結び付けます。(:keyword:`global` 文を使えば、特定の変数がグローバルスコープ に +あることを示せます。) .. _tut-firstclasses: クラス初見 ========== -クラスでは、新しい構文を少しと、三つの新たなオブジェクト型、そして新たな意 味付けをいくつか取り入れています。 - -.. % A First Look at Classes -.. % % Classes introduce a little bit of new syntax, three new object types, -.. % % and some new semantics. - +クラスでは、新しい構文を少しと、三つの新たなオブジェクト型、 +そして新たな意味付けをいくつか取り入れています。 .. _tut-classdefinition: クラス定義の構文 ---------------- -クラス定義の最も単純な形式は、以下のようになります: - -.. % Class Definition Syntax -.. % % The simplest form of class definition looks like this: +クラス定義の最も単純な形式は、次のようになります。 :: @@ -316,44 +226,28 @@ . <文-N> -関数定義 (:keyword:`def` 文) と同様、クラス定義が効果をもつにはまず実行しな ければなりません。 (クラス定義を :keyword:`if` +関数定義 (:keyword:`def` 文) と同様、クラス定義が効果をもつにはまず実行 +しなければなりません。 (クラス定義を :keyword:`if` 文の分岐先や関数内部に置くことも、考え方としてはありえます。) -.. % % Class definitions, like function definitions -.. % % (\keyword{def} statements) must be executed before they have any -.. % % effect. (You could conceivably place a class definition in a branch -.. % % of an \keyword{if} statement, or inside a function.) - -実際には、クラス定義の内側にある文は、通常は関数定義になりますが、他の文を 書くこともでき、それがそれが役に立つこともあります --- -これについては後で述べます。クラス内の関数定義は通常、メソッドの呼び出し規 約で決められた独特の形式の引数リストを持ちます --- これについても後で述べま す。 - -.. % % In practice, the statements inside a class definition will usually be -.. % % function definitions, but other statements are allowed, and sometimes -.. % % useful --- we'll come back to this later. The function definitions -.. % % inside a class normally have a peculiar form of argument list, -.. % % dictated by the calling conventions for methods --- again, this is -.. % % explained later. - -クラス定義に入ると、新たな名前空間が作成され、ローカルな名前空間として使わ れます --- 従って、ローカルな変数に対する -全ての代入はこの新たな名前空間に名要ります。特に、関数定義を行うと、新たな 関数の名前はこの名前空間に結び付けられます。 - -.. % % When a class definition is entered, a new namespace is created, and -.. % % used as the local scope --- thus, all assignments to local variables -.. % % go into this new namespace. In particular, function definitions bind -.. % % the name of the new function here. - -クラス定義から普通に (定義の終端に到達して) 抜けると、 *クラスオブジェクト (class object)* が生成されます。 -クラスオブジェクトは、基本的にはクラス定義で作成された名前空間の内容をくる むラッパ (wrapper) です; クラスオブジェクトについては -次の節で詳しく学ぶことにします。(クラス定義に入る前に有効だった) 元のローカ ルスコープが復帰し、生成されたクラスオブジェクトは -復帰したローカルスコープにクラス定義のヘッダで指定した名前 (上の例で は :class:`ClassName`) で結び付けられます。 - -.. % % When a class definition is left normally (via the end), a \emph{class -.. % % object} is created. This is basically a wrapper around the contents -.. % % of the namespace created by the class definition; we'll learn more -.. % % about class objects in the next section. The original local scope -.. % % (the one in effect just before the class definitions was entered) is -.. % % reinstated, and the class object is bound here to the class name given -.. % % in the class definition header (\class{ClassName} in the example). +実際には、クラス定義の内側にある文は、通常は関数定義になりますが、他の文を +書くこともでき、それが役に立つこともあります --- これについては後で述べま す。 +クラス内の関数定義は通常、メソッドの呼び出し規約で決められた独特の形式の +引数リストを持ちます --- これについても後で述べます。 + +クラス定義に入ると、新たな名前空間が作成され、ローカルな名前空間として +使われます --- 従って、ローカルな変数に対する全ての代入はこの新たな名前空間 に +入ります。 +特に、関数定義を行うと、新たな関数の名前はこの名前空間に結び付けられます。 + +クラス定義から普通に (定義の終端に到達して) 抜けると、 +*クラスオブジェクト (class object)* が生成されます。 +クラスオブジェクトは、基本的にはクラス定義で作成された名前空間の内容をくる む +ラッパ (wrapper) です。 +クラスオブジェクトについては次の節で詳しく学ぶことにします。 +(クラス定義に入る前に有効だった) 元のローカルスコープが復帰し、生成された +クラスオブジェクトは復帰したローカルスコープにクラス定義のヘッダで指定した 名前 +(上の例では :class:`ClassName`) で結び付けられます。 .. _tut-classobjects: @@ -361,20 +255,13 @@ クラスオブジェクト ------------------ -クラス・オブジェクトでは2種類の演算: 属性参照とインスタンス生成をサポート しています。 - -.. % Class Objects -.. % % Class objects support two kinds of operations: attribute references -.. % % and instantiation. - -*属性参照 (attribute reference)* は、Python におけるすべての属性参照で使わ れている標準的な構文、 ``obj.name`` -を使います。クラスオブジェクトが生成された際にクラスの名前空間にあった名前 すべてが有効な属性名です。従って、以下のようなクラス定義: - -.. % % \emph{Attribute references} use the standard syntax used for all -.. % % attribute references in Python: \code{obj.name}. Valid attribute -.. % % names are all the names that were in the class's namespace when the -.. % % class object was created. So, if the class definition looked like -.. % % this: +クラス・オブジェクトでは2種類の演算、属性参照とインスタンス生成を +サポートしています。 + +*属性参照 (attribute reference)* は、Python におけるすべての属性参照で +使われている標準的な構文、 ``obj.name`` を使います。 +クラスオブジェクトが生成された際にクラスの名前空間にあった名前すべてが +有効な属性名です。従って、以下のようなクラス定義では、 :: @@ -384,67 +271,48 @@ def f(self): return 'hello world' -では、 ``MyClass.i`` と ``MyClass.f`` は妥当な属性参照であり、それぞれ整数 と関数オブジェクトを返します。 -クラス属性に代入を行うこともできます。従って、 ``MyClass.i`` の値を代入して 変更できます。 ``__doc__`` -も有効な属性で、そのクラスに属している docstring、この場合は ``"A simple example class"`` を返します。 - -.. % % then \code{MyClass.i} and \code{MyClass.f} are valid attribute -.. % % references, returning an integer and a method object, respectively. -.. % % Class attributes can also be assigned to, so you can change the value -.. % % of \code{MyClass.i} by assignment. \member{__doc__} is also a valid -.. % % attribute, returning the docstring belonging to the class: \code{"A -.. % % simple example class"}). - -クラスの *インスタンス生成 (instantiation)* には関数のような表記法を使いま す。クラスオブジェクトのことを、単にクラスの新しい -インスタンスを返すパラメタを持たない関数かのように扱います。例えば (上記の クラスでいえば): - -.. % % Class \emph{instantiation} uses function notation. Just pretend that -.. % % the class object is a parameterless function that returns a new -.. % % instance of the class. For example (assuming the above class): +``MyClass.i`` と ``MyClass.f`` は妥当な属性参照であり、それぞれ整数と +関数オブジェクトを返します。 +クラス属性に代入を行うこともできます。 +従って、 ``MyClass.i`` の値を代入して変更できます。 +``__doc__`` も有効な属性で、そのクラスに属している docstring、 +この場合は ``"A simple example class"`` を返します。 + +クラスの *インスタンス生成 (instantiation)* には関数のような表記法を使いま す。 +クラスオブジェクトのことを、単にクラスの新しいインスタンスを返す +パラメタを持たない関数かのように扱います。例えば (上記のクラスでいえば)、 :: x = MyClass() -は、クラスの新しい *インスタンス (instance)* を生成し、そのオブジェクトを ローカル変数 ``x`` へ代入します。 - -.. % % creates a new \emph{instance} of the class and assigns this object to -.. % % the local variable \code{x}. - -インスタンス生成操作 (クラスオブジェクトの "呼出し") を行うと、空のオブジェ クト (empty object) を生成します。多くのクラスは、 -オブジェクトを作成する際に、カスタマイズされた特定の初期状態になってほしい と望んでいます。従って、クラスでは :meth:`__init__` -という名前の特別なメソッド定義することができます。例えば以下のようにします: - -.. % % The instantiation operation (``calling'' a class object) creates an -.. % % empty object. Many classes like to create objects with instances -.. % % customized to a specific initial state. -.. % % Therefore a class may define a special method named -.. % % \method{__init__()}, like this: +は、クラスの新しい *インスタンス (instance)* を生成し、そのオブジェクトを +ローカル変数 ``x`` へ代入します。 + +このクラスのインスタンス生成操作 (クラスオブジェクトの "呼出し") を行うと、 +空のオブジェクトを生成します。 +多くのクラスは、オブジェクトを作成する際に、カスタマイズされた特定の初期状 態に +なってほしいと望んでいます。そのために、クラスには :meth:`__init__` +という名前の特別なメソッド定義することができます。例えば次のようにします。 :: def __init__(self): self.data = [] -クラスが :meth:`__init__` メソッドを定義している場合、クラスのインスタンス を生成すると、新しく生成されたクラスインスタンスに対して自動的に -:meth:`__init__` を呼び出します。従って、この例では、新たな初期済みのインス タンスを以下のようにして得ることができます: - -.. % % When a class defines an \method{__init__()} method, class -.. % % instantiation automatically invokes \method{__init__()} for the -.. % % newly-created class instance. So in this example, a new, initialized -.. % % instance can be obtained by: +クラスが :meth:`__init__` メソッドを定義している場合、クラスのインスタンス を +生成すると、新しく生成されたクラスインスタンスに対して自動的 に :meth:`__init__` +を呼び出します。従って、この例では、新たな初期済みのインスタンスを次のよう に +して得ることができます。 :: x = MyClass() -もちろん、より大きな柔軟性を持たせるために、 :meth:`__init__` メソッドに複 数の引数をもたせることができます。 -その場合、クラスのインスタンス生成操作に渡された引数は :meth:`__init__` に 渡されます。例えば以下のように: - -.. % % Of course, the \method{__init__()} method may have arguments for -.. % % greater flexibility. In that case, arguments given to the class -.. % % instantiation operator are passed on to \method{__init__()}. For -.. % % example, +もちろん、より大きな柔軟性を持たせるために、 :meth:`__init__` メソッドに複 数の +引数をもたせることができます。 +その場合、次の例のように、クラスのインスタンス生成操作に渡された引数は +:meth:`__init__` に渡されます。 :: @@ -463,26 +331,15 @@ インスタンスオブジェクト ------------------------ -ところで、インスタンスオブジェクトを使うと何ができるのでしょうか?インスタ ンスオブジェクトが理解できる唯一の操作は、属性の参照です。 +ところで、インスタンスオブジェクトを使うと何ができるのでしょうか? +インスタンスオブジェクトが理解できる唯一の操作は、属性の参照です。 有効な属性の名前には二種類(データ属性およびメソッド)あります。 -.. % Instance Objects -.. % % Now what can we do with instance objects? The only operations -.. % % understood by instance objects are attribute references. There are -.. % % two kinds of valid attribute names, data attributes and methods. - -*データ属性 (data attribute)* は、これは Smalltalk の "インスタンス変数" (instance variable) や C++の -"データメンバ" (data member) に相当します。データ属性を宣言する必要はありま せん; ローカルな変数と同様に、 -これらの属性は最初に代入された時点で湧き出てきます。例えば、上で生成し た :class:`MyClass` のインスタンス ``x`` に対して、 -以下のコード断片を実行すると、値 ``16`` を印字し、 ``x`` の痕跡は残りませ ん。 - -.. % % \emph{data attributes} correspond to -.. % % ``instance variables'' in Smalltalk, and to ``data members'' in -.. % % \Cpp. Data attributes need not be declared; like local variables, -.. % % they spring into existence when they are first assigned to. For -.. % % example, if \code{x} is the instance of \class{MyClass} created above, -.. % % the following piece of code will print the value \code{16}, without -.. % % leaving a trace: +*データ属性 (data attribute)* は、これは Smalltalk の "インスタンス変数" や +C++の "データメンバ" に相当します。データ属性を宣言する必要はありません。 +ローカルな変数と同様に、これらの属性は最初に代入された時点で湧き出てきま す。 +例えば、上で生成した :class:`MyClass` のインスタンス ``x`` に対して、 +次のコードを実行すると、値 ``16`` を印字し、 ``x`` の痕跡は残りません。 :: @@ -492,35 +349,24 @@ print x.counter del x.counter -もうひとつのインスタンス属性は *メソッド (method)* です。メソッドとは、オブ ジェクトに "属している" 関数のことです。(Python -では、メソッドという用語はクラスインスタンスだけのものではありません: オブ ジェクト型にもメソッドを持つことができます。例えば、リストオブジェクトには、 -append, insert, remove, sort などといったメソッドがあります。とはいえ、以下 では特に明記しない限り、クラスの -インスタンスオブジェクトのメソッドだけを意味するものとして使うことにしま す。) - -.. % % The other kind of instance attribute reference is a \emph{method}. -.. % % A method is a function that ``belongs to'' an -.. % % object. (In Python, the term method is not unique to class instances: -.. % % other object types can have methods as well. For example, list objects have -.. % % methods called append, insert, remove, sort, and so on. However, -.. % % in the following discussion, we'll use the term method exclusively to mean -.. % % methods of class instance objects, unless explicitly stated otherwise.) +もうひとつのインスタンス属性は *メソッド (method)* です。メソッドとは、 +オブジェクトに "属している" 関数のことです。(Python では、メソッドという +用語はクラスインスタンスだけのものではありません。 +オブジェクト型にもメソッドを持つことができます。例えば、リストオブジェクト には、 +append, insert, remove, sort などといったメソッドがあります。 +とはいえ、以下では特に明記しない限り、クラスのインスタンスオブジェクトの +メソッドだけを意味するものとして使うことにします。) .. index:: object: method -インスタンスオブジェクトで有効なメソッド名は、そのクラスによります。定義に より、クラスの全てのo関数オブジェクトである属性が -インスタンスオブジェクトの妥当なメソッド名に決まります。従って、例では、 ``MyClass.f`` は関数なので、 ``x.f`` -はメソッドの参照として有効です。しかし、 ``MyClass.i`` は関数ではないの で、 ``x.i`` はメソッドの参照 -として有効ではありません。 ``x.f`` は ``MyClass.f`` と同じものではありませ ん --- 関数オブジェクトではなく、 *メソッドオブジェクト -(method object)* です。 - -.. % % Valid method names of an instance object depend on its class. By -.. % % definition, all attributes of a class that are function -.. % % objects define corresponding methods of its instances. So in our -.. % % example, \code{x.f} is a valid method reference, since -.. % % \code{MyClass.f} is a function, but \code{x.i} is not, since -.. % % \code{MyClass.i} is not. But \code{x.f} is not the same thing as -.. % % \code{MyClass.f} --- it is a \obindex{method}\emph{method object}, not -.. % % a function object. +インスタンスオブジェクトで有効なメソッド名は、そのクラスによります。 +定義により、クラスの全てのo関数オブジェクトである属性がインスタンス +オブジェクトの妥当なメソッド名に決まります。 +従って、例では、 ``MyClass.f`` は関数なので、 ``x.f`` はメソッドの参照とし て +有効です。しかし、 ``MyClass.i`` は関数ではないので、 ``x.i`` はメソッドの 参照 +として有効ではありません。 +``x.f`` は ``MyClass.f`` と同じものではありません --- 関数オブジェクトでは なく、 +*メソッドオブジェクト (method object)* です。 .. _tut-methodobjects: @@ -528,23 +374,16 @@ メソッドオブジェクト -------------------- -普通、メソッドはバインドされた直後に呼び出されます: - -.. % Method Objects -.. % % Usually, a method is called right after it is bound: +普通、メソッドはバインドされた直後に呼び出されます。 :: x.f() :class:`MyClass` の例では、上のコードは文字列 ``'hello world'`` を返すでし ょう。 -しかしながら、必ずしもメソッドをその場で呼び出さなければならないわけではあ りません: ``x.f`` はメソッドオブジェクトであり、 -どこかに記憶しておいて後で呼び出すことができます。例えば以下のコード: - -.. % % In the \class{MyClass} example, this will return the string \code{'hello world'}. -.. % % However, it is not necessary to call a method right away: -.. % % \code{x.f} is a method object, and can be stored away and called at a -.. % % later time. For example: +しかしながら、必ずしもメソッドをその場で呼び出さなければならないわけでは +ありません。 ``x.f`` はメソッドオブジェクトであり、どこかに記憶しておいて +後で呼び出すことができます。例えば次のコードは、 :: @@ -552,132 +391,78 @@ while True: print xf() -は、 ``hello world`` を時が終わるまで印字し続けるでしょう。 - -.. % % will continue to print \samp{hello world} until the end of time. - -メソッドが呼び出されるときには実際には何が起きているのでしょう か? :meth:`f` の関数定義では引数を一つ指定していたにもかかわらず、上記では -``x.f`` が引数なしで呼び出されたことに気付いているかもしれませんね。引数は どうなったのでしょうか?たしか、引数が必要な関数を -引数無しで呼び出すと、Python が例外を送出するはずです --- たとえその引数が 実際には使われなくても…。 - -.. % % What exactly happens when a method is called? You may have noticed -.. % % that \code{x.f()} was called without an argument above, even though -.. % % the function definition for \method{f} specified an argument. What -.. % % happened to the argument? Surely Python raises an exception when a -.. % % function that requires an argument is called without any --- even if -.. % % the argument isn't actually used... - -実際、もう答は想像できているかもしれませんね: メソッドについて特別なことと して、オブジェクトが関数の第 1 引数として渡される、 -ということがあります。我々の例では、 ``x.f()`` という呼び出しは、 ``MyClass.f(x)`` と厳密に等価なものです。一般に、 *n* -個の引数リストもったメソッドの呼出しは、そのメソッドのオブジェクトを最初の 引数の前に挿入した引数リストでメソッドに対応する関数を呼び出すことと等価で す。 - -.. % % Actually, you may have guessed the answer: the special thing about -.. % % methods is that the object is passed as the first argument of the -.. % % function. In our example, the call \code{x.f()} is exactly equivalent -.. % % to \code{MyClass.f(x)}. In general, calling a method with a list of -.. % % \var{n} arguments is equivalent to calling the corresponding function -.. % % with an argument list that is created by inserting the method's object -.. % % before the first argument. - -もしもまだメソッドの働きかたを理解できなければ、一度実装を見てみると事情が よく分かるかもしれません。 +``hello world`` を時が終わるまで印字し続けるでしょう。 + +メソッドが呼び出されるときには実際には何が起きているのでしょうか? +:meth:`f` の関数定義では引数を一つ指定していたにもかかわらず、上の例では +``x.f`` が引数なしで呼び出されています。引数はどうなったのでしょうか? +たしか、引数が必要な関数を引数無しで呼び出すと、 Python が例外を +送出するはずです --- たとえその引数が実際には使われなくても…。 + +もう答は想像できているかもしれませんね。 +メソッドについて特別なこととして、オブジェクトが関数の第1引数として渡されま す。 +例では、 ``x.f()`` という呼び出しは、 ``MyClass.f(x)`` と厳密に等価なもので す。 +一般に、 *n* 個の引数リストもったメソッドの呼出しは、そのメソッドの +オブジェクトを最初の引数の前に挿入した引数リストでメソッドに対応する関数を +呼び出すことと等価です。 + +もしまだメソッドの動作を理解できなければ、一度実装を見てみると事情がよく分 かる +かもしれません。 データ属性ではないインスタンス属性が参照された時は、そのクラスが検索されま す。 -その名前が有効なクラス属性を表している関数オブジェクトなら、インスタンスオ ブジェクトと見つかった関数オブジェクト (へのポインタ) -を抽象オブジェクト: すなわちメソッドオブジェクトにパック (pack) して作成し ます。 +その名前が有効なクラス属性を表している関数オブジェクトなら、インスタンス +オブジェクトと見つかった関数オブジェクト (へのポインタ) を抽象オブジェク ト、 +すなわちメソッドオブジェクトにパックして作成します。 メソッドオブジェクトが引数リストと共に呼び出されるとき、インスタンスオブジ ェクトと 渡された引数リストから新しい引数リストを作成して、元の関数オブジェクトを 新しい引数リストで呼び出します。 -.. % % If you still don't understand how methods work, a look at the -.. % % implementation can perhaps clarify matters. When an instance -.. % % attribute is referenced that isn't a data attribute, its class is -.. % % searched. If the name denotes a valid class attribute that is a -.. % % function object, a method object is created by packing (pointers to) -.. % % the instance object and the function object just found together in an -.. % % abstract object: this is the method object. When the method object is -.. % % called with an argument list, it is unpacked again, a new argument -.. % % list is constructed from the instance object and the original argument -.. % % list, and the function object is called with this new argument list. - .. _tut-remarks: いろいろな注意点 ================ -.. % Random Remarks -.. % % [These should perhaps be placed more carefully...] -.. これらはおそらくもっと注意深く配置すべきだろう… - -データ属性は同じ名前のメソッド属性を上書きしてしまいます; 大規模なプログラ ムでみつけにくいバグを引き起こすことがある -この偶然的な名前の衝突を避けるには、衝突の可能性を最小限にするような規約を 使うのが賢明です。 -可能な規約としては、メソッド名を大文字で始める、データ属性名の先頭に短い一 意的な文字列 (あるいはただの下線) をつける、またメソッドには動詞、 +データ属性は同じ名前のメソッド属性を上書きしてしまいます。 +大規模なプログラムでみつけにくいバグを引き起こすことがあるこの偶然的な名前 の +衝突を避けるには、衝突の可能性を最小限にするような規約を使うのが賢明です。 +可能な規約としては、メソッド名を大文字で始める、データ属性名の先頭に短い +一意な文字列 (あるいはただの下線) をつける、またメソッドには動詞、 データ属性には名詞を用いる、などがあります。 -.. % % Data attributes override method attributes with the same name; to -.. % % avoid accidental name conflicts, which may cause hard-to-find bugs in -.. % % large programs, it is wise to use some kind of convention that -.. % % minimizes the chance of conflicts. Possible conventions include -.. % % capitalizing method names, prefixing data attribute names with a small -.. % % unique string (perhaps just an underscore), or using verbs for methods -.. % % and nouns for data attributes. - -データ属性は、メソッドから参照できると同時に、通常のオブジェクトのユーザ ("クライアント") からも参照できます。言い換えると、 -クラスは純粋な抽象データ型として使うことができません。実際、 Python では、 データ隠蔽を補強するための機構はなにもありません --- -データの隠蔽はすべて規約に基づいています。(逆に、C 言語で書かれた Python の 実装では実装の詳細を完全に隠蔽し、必要に応じてオブジェクト -へのアクセスを制御できます; この機構は C 言語で書かれた Python 拡張で使うこ とができます) - -.. % % Data attributes may be referenced by methods as well as by ordinary -.. % % users (``clients'') of an object. In other words, classes are not -.. % % usable to implement pure abstract data types. In fact, nothing in -.. % % Python makes it possible to enforce data hiding --- it is all based -.. % % upon convention. (On the other hand, the Python implementation, -.. % % written in C, can completely hide implementation details and control -.. % % access to an object if necessary; this can be used by extensions to -.. % % Python written in C.) - -クライアントはデータ属性を注意深く扱うべきです --- クライアントは、メソッド を使うことで維持しているデータ属性の不変式を踏みにじり、 -台無しにするかもしれません。クライアントは、名前の衝突が回避されている限 り、メソッドの有効性に -影響を及ぼすことなくインスタンスに独自の属性を追加することができる、という ことに注意してください --- ここでも、名前付けの規約は -頭痛の種を無くしてくれます。 - -.. % % Clients should use data attributes with care --- clients may mess up -.. % % invariants maintained by the methods by stamping on their data -.. % % attributes. Note that clients may add data attributes of their own to -.. % % an instance object without affecting the validity of the methods, as -.. % % long as name conflicts are avoided --- again, a naming convention can -.. % % save a lot of headaches here. - -データ属性を (またはその他のメソッドも!) メソッドの中で参照するための短縮 された記法はありません。私は、この仕様が実際にメソッドの -可読性を高めていると考えています: あるメソッドを眺めているときにローカルな 変数とインスタンス変数を混同する可能性はまったくありません。 - -.. % % There is no shorthand for referencing data attributes (or other -.. % % methods!) from within methods. I find that this actually increases -.. % % the readability of methods: there is no chance of confusing local -.. % % variables and instance variables when glancing through a method. +データ属性は、メソッドから参照できると同時に、通常のオブジェクトのユーザ +("クライアント") からも参照できます。 +言い換えると、クラスは純粋な抽象データ型として使うことができません。 +実際、 Python では、データ隠蔽を補強するための機構はなにもありません --- +データの隠蔽はすべて規約に基づいています。 +(逆に、C 言語で書かれた Python の実装では実装の詳細を完全に隠蔽し、 +必要に応じてオブジェクトへのアクセスを制御できます。 +この機構は C 言語で書かれた Python 拡張で使うことができます。) + +クライアントはデータ属性を注意深く扱うべきです --- クライアントは、メソッド が +維持しているデータ属性の不変式を踏みにじり、台無しにするかもしれません。 +クライアントは、名前の衝突が回避されている限り、メソッドの有効性に影響を +及ぼすことなくインスタンスに独自の属性を追加することができる、ということに +注意してください --- ここでも、名前付けの規約は頭痛の種を無くしてくれます。 + +メソッドの中から、データ属性を (または別のメソッドも!) 参照するための +短縮された記法はありません。 +私は、この仕様がメソッドの可読性を高めていると感じています。 +あるメソッドを眺めているときにローカルな変数とインスタンス変数を +はっきり区別できるからです。 よく、メソッドの最初の引数を ``self`` と呼びます。 -この名前付けは単なる慣習でしかありません: ``self`` という名前は、 +この名前付けは単なる慣習でしかありません。 ``self`` という名前は、 Python では何ら特殊な意味を持ちません。 -とはいえ、この慣行に従わないと、コードは他の Python プログラマにとってやや 読みにくいものとなります。 -また、 *クラスブラウザ (class browser)* プログラムがこの慣行をあてにして書 かれているかもしれません。 - -.. % % Often, the first argument of a method is called -.. % % \code{self}. This is nothing more than a convention: the name -.. % % \code{self} has absolutely no special meaning to Python. (Note, -.. % % however, that by not following the convention your code may be less -.. % % readable to other Python programmers, and it is also conceivable that -.. % % a \emph{class browser} program might be written that relies upon such a -.. % % convention.) - -クラス属性である関数オブジェクトはいずれも、そのクラスのインスタンスのため のメソッドを定義しています。関数定義は、テキスト上では -クラス定義の中に入っていなければならないわけではありません: 関数オブジェク トをクラスのローカルな変数の中に代入するのも OK です。 -例えば以下のコードのようにします: - -.. % % Any function object that is a class attribute defines a method for -.. % % instances of that class. It is not necessary that the function -.. % % definition is textually enclosed in the class definition: assigning a -.. % % function object to a local variable in the class is also ok. For -.. % % example: +とはいえ、この慣行に従わないと、コードは他の Python プログラマにとってやや +読みにくいものとなります。 +また、 *クラスブラウザ (class browser)* プログラムがこの慣行をあてにして +書かれているかもしれません。 + +クラス属性である関数オブジェクトはいずれも、そのクラスのインスタンスのため の +メソッドを定義しています。 +関数定義は、テキスト上でクラス定義の中に入っている必要はありません。 +関数オブジェクトをクラスのローカルな変数の中に代入するのも OK です。 +例えば以下のコードのようにします。 :: @@ -691,20 +476,14 @@ return 'hello world' h = g -これで、 ``f`` 、 ``g`` 、および ``h`` は、すべて :class:`C` の属性であり関 数オブジェクトを参照しています。 -従って、これら全ては、 :class:`C` のインスタンスのメソッドとなります --- ``h`` は ``g`` と全く等価です。これを実践しても、大抵は -単にプログラムの読者に混乱をもたらすだけなので注意してください。 - -.. % % Now \code{f}, \code{g} and \code{h} are all attributes of class -.. % % \class{C} that refer to function objects, and consequently they are all -.. % % methods of instances of \class{C} --- \code{h} being exactly equivalent -.. % % to \code{g}. Note that this practice usually only serves to confuse -.. % % the reader of a program. - -メソッドは、 ``self`` 引数のメソッド属性を使って、他のメソッドを呼び出すこ とができます: - -.. % % Methods may call other methods by using method attributes of the -.. % % \code{self} argument: +これで、 ``f`` 、 ``g`` 、および ``h`` は、すべて :class:`C` の属性であり +関数オブジェクトを参照しています。 +従って、これら全ては、 :class:`C` のインスタンスのメソッドとなります --- +``h`` は ``g`` と全く等価です。これを実践しても、大抵は単にプログラムの読者 に +混乱をもたらすだけなので注意してください。 + +メソッドは、 ``self`` 引数のメソッド属性を使って、他のメソッドを呼び出すこ とが +できます。 :: @@ -718,24 +497,17 @@ self.add(x) メソッドは、通常の関数と同じようにしてグローバルな名前を参照します。 -あるメソッドに関連付けられたグローバルなスコープは、クラス定義の入っている モジュールになります。 (クラス自体はグローバルなスコープとして用いられることはありません。) -メソッドでグローバルなデータを使う良い理由はほとんどありませんが、グローバ ルなスコープを使う合法的な使い方は多々あります: -一つ挙げると、メソッド内では、グローバルなスコープに import された関数やモ ジュールや、 -その中で定義された関数やクラスを使うことができます。 +メソッドでグローバルなデータを使う良い理由はほとんどありませんが、 +グローバルなスコープを使うべき場面は多々あります。 +一つ挙げると、メソッド内から、グローバルなスコープに import された関数やモ ジュールや、 +そのモジュール中で定義された関数やクラスを使うことができます。 通常、メソッドの入っているクラス自体はグローバルなスコープ内で定義されてい ます。 -次の章では、メソッドが自分のクラスを参照する理由として正当なものを見てみま しょう。 - -.. % % Methods may reference global names in the same way as ordinary -.. % % functions. The global scope associated with a method is the module -.. % % containing the class definition. (The class itself is never used as a -.. % % global scope!) While one rarely encounters a good reason for using -.. % % global data in a method, there are many legitimate uses of the global -.. % % scope: for one thing, functions and modules imported into the global -.. % % scope can be used by methods, as well as functions and classes defined -.. % % in it. Usually, the class containing the method is itself defined in -.. % % this global scope, and in the next section we'll find some good -.. % % reasons why a method would want to reference its own class! +次の節では、メソッドが自分のクラスを参照する理由として正当なものを見てみま しょう。 + +.. The global scope associated... のくだりだが、グローバルスコープは + 関数定義のあるモジュールになる。とりあえず以下の訳を省いた状態にしてお く。 + >あるメソッドに関連付けられたグローバルなスコープは、クラス定義の入って いるモジュールになります。 個々の値はオブジェクトなので、 *クラス* (*型* とも言います) を持っていま す。 それは ``object.__class__`` に保持されています。 @@ -745,13 +517,9 @@ 継承 ==== -言うまでもなく、継承の概念をサポートしない言語機能は "クラス" と呼ぶに値し ません。導出クラス (derived class) を定義する構文は以下のように -なります: - -.. % Inheritance -.. % % Of course, a language feature would not be worthy of the name ``class'' -.. % % without supporting inheritance. The syntax for a derived class -.. % % definition looks like this: +言うまでもなく、継承の概念をサポートしない言語機能は "クラス" と +呼ぶに値しません。導出クラス (derived class) を定義する構文は次のように +なります。 :: @@ -763,73 +531,50 @@ <文-N> 基底クラス (base class) の名前 :class:`BaseClassName` は、 -導出クラス定義の入っているスコープで定義されていなければなりません。基底ク ラス名のかわりに任意の式を入れることもできます。これは以下のように、 - -.. % % The name \class{BaseClassName} must be defined in a scope containing -.. % % the derived class definition. In place of a base class name, other -.. % % arbitrary expression is also allowed. This can be useful, for -.. % % example, when the base class is defined in another module: +導出クラス定義の入っているスコープで定義されていなければなりません。 +基底クラス名のかわりに任意の式を入れることもできます。これは次の例のよう に、 +基底クラスが別モジュールで定義されているときに便利なことがあります。 :: class DerivedClassName(modname.BaseClassName): -基底クラスが別モジュールで定義されているときに便利なことがあります。 - -導出クラス定義の実行は、基底クラスの場合と同じように進められます。クラスオ ブジェクトが構築される時、基底クラスが記憶されます。 -記憶された基底クラスは、属性参照を解決するために使われます: 要求された属性 がクラスに見つからなかった場合、基底クラスに検索 -が進みます。この規則は、基底クラスが他の何らかのクラスから導出されたもので あった場合、再帰的に適用されます。 - -.. % % Execution of a derived class definition proceeds the same as for a -.. % % base class. When the class object is constructed, the base class is -.. % % remembered. This is used for resolving attribute references: if a -.. % % requested attribute is not found in the class, search proceeds to look in the -.. % % base class. This rule is applied recursively if the base class itself -.. % % is derived from some other class. - -導出クラスのインスタンス化では、特別なことは何もありません: ``DerivedClassName()`` はクラスの新たなインスタンスを生成します。 -メソッドの参照は以下のようにしてい解決されます: まず対応するクラス属性が検 索されます。検索は、必要に応じ、基底クラス連鎖を下って行われ、 -検索の結果として何らかの関数オブジェクトがもたらされた場合、メソッド参照は 有効なものとなります。 - -.. % % There's nothing special about instantiation of derived classes: -.. % % \code{DerivedClassName()} creates a new instance of the class. Method -.. % % references are resolved as follows: the corresponding class attribute -.. % % is searched, descending down the chain of base classes if necessary, -.. % % and the method reference is valid if this yields a function object. - -導出クラスは基底クラスのメソッドを上書き (override) してもかまいません。メ ソッドは同じオブジェクトの別のメソッドを呼び出す際に何ら特殊な権限を -持ちません。このため、ある基底クラスのメソッドが、同じ基底クラスで定義され ているもう一つのメソッド呼び出しを行っている場合、 -導出クラスで上書きされた何らかのメソッドが呼び出されることになるかもしれま せん。 (C++ プログラマへ: Python では、すべてのメソッドは事実上 -``virtual`` です。) - -.. % % Derived classes may override methods of their base classes. Because -.. % % methods have no special privileges when calling other methods of the -.. % % same object, a method of a base class that calls another method -.. % % defined in the same base class may end up calling a method of -.. % % a derived class that overrides it. (For \Cpp{} programmers: all methods -.. % % in Python are effectively \keyword{virtual}.) - -導出クラスで上書きしているメソッドでは、実際は単に基底クラスの同名のメソッ ドを置き換えるだけではなく、拡張を行いたいかもしれません。 -基底クラスのメソッドを直接呼び出す簡単な方法があります: 単に ``BaseClassName.methodname(self, arguments)`` -を呼び出すだけです。 +導出クラス定義の実行は、基底クラスの場合と同じように進められます。 +クラスオブジェクトが構築される時、基底クラスが記憶されます。 +記憶された基底クラスは、属性参照を解決するために使われます。 +要求された属性がクラスに見つからなかった場合、基底クラスに検索が進みます。 +この規則は、基底クラスが他の何らかのクラスから導出されたものであった場合、 +再帰的に適用されます。 + +導出クラスのインスタンス化では、特別なことは何もありません。 +``DerivedClassName()`` はクラスの新たなインスタンスを生成します。 +メソッドの参照は次のようにしてい解決されます。 +まず対応するクラス属性が検索されます。検索は、必要に応じ、基底クラス連鎖を 下って +行われ、検索の結果として何らかの関数オブジェクトがもたらされた場合、 +メソッド参照は有効なものとなります。 + +導出クラスは基底クラスのメソッドを上書き (override) することができます。 +メソッドは同じオブジェクトの別のメソッドを呼び出す際に何ら特殊な権限を +持ちません。このため、ある基底クラスのメソッドが、同じ基底クラスで +定義されているもう一つのメソッド呼び出しを行っている場合、 +導出クラスで上書きされた何らかのメソッドが呼び出されることになるかもしれま せん。 +(C++ プログラマへ: Python では、すべてのメソッドは事実上 ``virtual`` で す。) + +導出クラスで上書きしているメソッドでは、基底クラスの同名のメソッドを置き換 える +のではなく、拡張したいのかもしれません。 +基底クラスのメソッドを直接呼び出す簡単な方法があります。 +単に ``BaseClassName.methodname(self, arguments)`` を呼び出すだけです。 この仕様は、場合によってはクライアントでも役に立ちます。 (この呼び出し方が動作するのは、基底クラスがグローバルスコープの ``BaseClassName`` -という名前で悪えっすされているときだけです。) - -.. % % An overriding method in a derived class may in fact want to extend -.. % % rather than simply replace the base class method of the same name. -.. % % There is a simple way to call the base class method directly: just -.. % % call \samp{BaseClassName.methodname(self, arguments)}. This is -.. % % occasionally useful to clients as well. (Note that this only works if -.. % % the base class is defined or imported directly in the global scope.) - -Python には継承に関係する 2 つの組み込み関数があります: - -* :func:`isinstance` を使うとインスタンスの型が調べられます: +という名前でアクセスできるときだけです。) + +Python には継承に関係する 2 つの組み込み関数があります。 + +* :func:`isinstance` を使うとインスタンスの型が調べられます。 ``isinstance(obj, int)`` は ``obj.__class__`` が :class:`int` や :class:`int` の導出クラスの場合に限り ``True`` になります。 -* :func:`issubclass` を使うとクラスの継承関係が調べられます: +* :func:`issubclass` を使うとクラスの継承関係が調べられます。 :class:`bool` は :class:`int` のサブクラスなので ``issubclass(bool, int)`` は ``True`` です。しかし、 :class:`unicode` は :class:`str` のサブクラスではない (単に共通の祖先 :class:`basestring` @@ -840,12 +585,8 @@ 多重継承 -------- -Python では、限られた形式の多重継承 (multiple inheritance) もサポートしてい ます。複数の基底クラスをもつクラス定義は以下のように -なります: - -.. % Multiple Inheritance -.. % % Python supports a limited form of multiple inheritance as well. A -.. % % class definition with multiple base classes looks like this: +Python では、限られた形式の多重継承 (multiple inheritance) もサポートしてい ます。 +複数の基底クラスをもつクラス定義は次のようになります。 ***The diff for this file has been truncated for email.***