# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001 Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # python-doc bot, 2025 # Rafael Fontenelle , 2025 # Takanori Suzuki , 2025 # TENMYO Masakazu, 2026 # Inada Naoki , 2026 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.15\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2026-10-23 18:01+0000\n" "PO-Revision-Date: 2025-09-16 00:02+0000\n" "Last-Translator: Inada Naoki , 2026\n" "Language-Team: Japanese (https://app.transifex.com/python-doc/teams/5390/" "ja/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: ja\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../../tutorial/classes.rst:5 msgid "Classes" msgstr "クラス" #: ../../tutorial/classes.rst:7 msgid "" "Classes provide a means of bundling data and functionality together. " "Creating a new class creates a new *type* of object, allowing new " "*instances* of that type to be made. Each class instance can have " "attributes attached to it for maintaining its state. Class instances can " "also have methods (defined by its class) for modifying its state." msgstr "" "クラスはデータと機能を組み合わせる方法を提供します。\n" "新規にクラスを作成することで、新しいオブジェクトの *型* を作成し、その型を持" "つ新しい *インスタンス* が作れます。\n" "クラスのそれぞれのインスタンスは自身の状態を保持する属性を持てます。\n" "クラスのインスタンスは、その状態を変更するための (そのクラスが定義する) メ" "ソッドも持てます。" msgid "" "Compared with other programming languages, Python's class mechanism adds " "classes with a minimum of new syntax and semantics. It is a mixture of the " "class mechanisms found in C++ and Modula-3. Python classes provide all the " "standard features of Object Oriented Programming: the class inheritance " "mechanism allows multiple base classes, a derived class can override any " "methods of its base class or classes, and a method can call the method of a " "base class with the same name. Objects can contain arbitrary amounts and " "kinds of data. As is true for modules, classes partake of the dynamic " "nature of Python: they are created at runtime, and can be modified further " "after creation." msgstr "" "Python のクラス機構は、ほかのプログラミング言語に比べて、新しく覚える構文や規" "則を最小限に抑えています。\n" "その仕組みは C++ と Modula-3 のクラス機構を組み合わせたものです。\n" "Python のクラスは、オブジェクト指向プログラミングの標準的な機能をすべて備えて" "います。\n" "複数の基底クラスを継承でき、派生クラスでは基底クラスのどのメソッドもオーバー" "ライドできます。\n" "また、メソッドから基底クラスの同名のメソッドを呼び出せます。\n" "オブジェクトに格納するデータの種類や数も自由です。\n" "モジュールと同様に、クラスも Python の動的な性質を持っています。\n" "クラスは実行時に作られ、作成後に変更することもできます。" msgid "" "In C++ terminology, normally class members (including the data members) are " "*public* (except see below :ref:`tut-private`), and all member functions are " "*virtual*. As in Modula-3, there are no shorthands for referencing the " "object's members from its methods: the method function is declared with an " "explicit first argument representing the object, which is provided " "implicitly by the call. As in Smalltalk, classes themselves are objects. " "This provides semantics for importing and renaming. Unlike C++ and " "Modula-3, built-in types can be used as base classes for extension by the " "user. Also, like in C++, most built-in operators with special syntax " "(arithmetic operators, subscripting etc.) can be redefined for class " "instances." msgstr "" "C++ の用語で言うと、クラスメンバはデータメンバも含めて通常 *public* です\n" "(例外については :ref:`tut-private` を参照してください)。\n" "メンバ関数はすべて *仮想関数 (virtual)* です。\n" "Modula-3 と同様に、メソッド内からオブジェクトのメンバを参照するための短縮記法" "はありません。\n" "メソッド関数の宣言では、オブジェクト自体を表す引数を最初に明示します。\n" "メソッドを呼び出すと、この引数にオブジェクトが暗黙的に渡されます。\n" "Smalltalk と同様に、クラス自体もオブジェクトなので、インポートしたり別の名前" "を付けたりできます。\n" "C++ や Modula-3 と違って、組み込み型を基底クラスにして拡張することもできま" "す。\n" "また、C++ と同様に、算術演算子や添字表記など特別な構文を使う組み込み演算子の" "多くは、\n" "クラスインスタンスに対する動作を再定義できます。" #: ../../tutorial/classes.rst:34 msgid "" "(Lacking universally accepted terminology to talk about classes, I will make " "occasional use of Smalltalk and C++ terms. I would use Modula-3 terms, " "since its object-oriented semantics are closer to those of Python than C++, " "but I expect that few readers have heard of it.)" msgstr "" "(クラスに関して普遍的な用語定義がないので、 Smalltalk と C++ の用語を場合に応" "じて使っていくことにします。 C++ よりも Modula-3 の方がオブジェクト指向の意味" "論が Python に近いので、 Modula-3 の用語を使いたいのですが、ほとんどの読者は " "Modula-3 についてしらないでしょうから。)" #: ../../tutorial/classes.rst:43 msgid "A Word About Names and Objects" msgstr "名前とオブジェクトについて" msgid "" "Objects have individuality, and multiple names (in multiple scopes) can be " "bound to the same object. This is known as aliasing in other languages. " "This is usually not appreciated on a first glance at Python, and can be " "safely ignored when dealing with immutable basic types (numbers, strings, " "tuples). However, aliasing has a possibly surprising effect on the " "semantics of Python code involving mutable objects such as lists, " "dictionaries, and most other types. This is usually used to the benefit of " "the program, since aliases behave like pointers in some respects. For " "example, passing an object is cheap since only a pointer is passed by the " "implementation; and if a function modifies an object passed as an argument, " "the caller will see the change --- this eliminates the need for two " "different argument passing mechanisms as in Pascal." msgstr "" "オブジェクトはそれぞれ固有の存在ですが、同じオブジェクトに複数のスコープから" "複数の名前を束縛できます。\n" "ほかの言語では、これをエイリアス (別名) と呼びます。\n" "Python を学び始めたばかりでは、この仕組みの重要性は分かりにくいかもしれませ" "ん。\n" "数値、文字列、タプルのようなイミュータブル (変更できない) な基本型を扱うとき" "は、気にしなくても問題ありません。\n" "一方、リストや辞書など多くの型のミュータブル (変更できる) なオブジェクトを扱" "うコードでは、\n" "エイリアスによって意外な動作が起こることがあります。\n" "エイリアスはいくつかの点でポインタのように振る舞うため、通常はその性質をプロ" "グラムに役立てられます。\n" "例えば、オブジェクトを渡す際に実装上渡されるのはポインタだけなので、処理の負" "担は小さくなります。\n" "また、関数が引数として受け取ったオブジェクトを変更すると、呼び出し側からもそ" "の変更が見えます。\n" "このため、Pascal のように引数の渡し方を 2 種類用意する必要がありません。" #: ../../tutorial/classes.rst:61 msgid "Python Scopes and Namespaces" msgstr "Python のスコープと名前空間" msgid "" "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." msgstr "" "クラスを紹介する前に、Python のスコープの規則について説明する必要がありま" "す。\n" "クラス定義は名前空間を巧みに利用するので、その動作を十分に理解するには、ス" "コープと名前空間の仕組みを知っておく必要があります。\n" "なお、この知識は高度なプログラミングを行う Python プログラマーなら誰にとって" "も役立ちます。" #: ../../tutorial/classes.rst:69 msgid "Let's begin with some definitions." msgstr "まず定義から始めましょう。" #: ../../tutorial/classes.rst:71 msgid "" "A *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 (containing " "functions such as :func:`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." msgstr "" "*名前空間 (namespace)* とは、名前からオブジェクトへの対応付け (mapping) で" "す。ほとんどの名前空間は、現状では Python の辞書として実装されていますが、そ" "のことは通常は (パフォーマンス以外では) 目立つことはないし、将来は変更される" "かもしれません。名前空間の例には、組込み名の集合 (:func:`abs` 等の関数や組込" "み例外名)、モジュール内のグローバルな名前、関数を呼び出したときのローカルな名" "前があります。オブジェクトの属性からなる集合もまた、ある意味では名前空間で" "す。名前空間について知っておくべき重要なことは、異なった名前空間にある名前の" "間には全く関係がないということです。例えば、二つの別々のモジュールの両方で関" "数 ``maximize`` という関数を定義することができ、定義自体は混同されることはあ" "りません --- モジュールのユーザは名前の前にモジュール名をつけなければなりませ" "ん。" #: ../../tutorial/classes.rst:82 msgid "" "By the way, I use the word *attribute* for any name following a dot --- for " "example, in the expression ``z.real``, ``real`` is an attribute of the " "object ``z``. Strictly speaking, references to names in modules are " "attribute references: in the expression ``modname.funcname``, ``modname`` is " "a module object and ``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! [#]_" msgstr "" "ところで、 *属性* という言葉は、ドットに続く名前すべてに対して使っています " "--- 例えば式 ``z.real`` で、 ``real`` はオブジェクト ``z`` の属性です。厳密に" "いえば、モジュール内の名前に対する参照は属性の参照です。式 ``modname." "funcname`` では、 ``modname`` はあるモジュールオブジェクトで、 ``funcname`` " "はその属性です。この場合には、モジュールの属性とモジュールの中で定義されてい" "るグローバル名の間には、直接的な対応付けがされます。これらの名前は同じ名前空" "間を共有しているのです! [#]_" #: ../../tutorial/classes.rst:90 msgid "" "Attributes may be read-only or writable. In the latter case, assignment to " "attributes is possible. Module attributes are writable: you can write " "``modname.the_answer = 42``. Writable attributes may also be deleted with " "the :keyword:`del` statement. For example, ``del modname.the_answer`` will " "remove the attribute :attr:`!the_answer` from the object named by " "``modname``." msgstr "" "属性は読取り専用にも、書込み可能にもできます。書込み可能であれば、属性に代入" "することができます。モジュール属性は書込み可能で、 ``modname.the_answer = " "42`` と書くことができます。書込み可能な属性は、 :keyword:`del` 文で削除するこ" "ともできます。例えば、 ``del modname.the_answer`` は、 ``modname`` で指定され" "たオブジェクトから属性 :attr:`!the_answer` を除去します。" #: ../../tutorial/classes.rst:96 msgid "" "Namespaces 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 :mod:" "`__main__`, so they have their own global namespace. (The built-in names " "actually also live in a module; this is called :mod:`builtins`.)" msgstr "" "名前空間は様々な時点で作成され、その寿命も様々です。組み込みの名前が入った名" "前空間は Python インタプリタが起動するときに作成され、決して削除されることは" "ありません。モジュールのグローバルな名前空間は、モジュール定義が読み込まれた" "ときに作成されます。通常、モジュールの名前空間は、インタプリタが終了するまで" "残ります。インタプリタのトップレベルで実行された文は、スクリプトファイルから" "読み出されたものでも対話的に読み出されたものでも、 :mod:`__main__` という名前" "のモジュールの一部分であるとみなされるので、独自の名前空間を持つことになりま" "す。 (組み込みの名前は実際にはモジュール内に存在します。そのモジュールは :" "mod:`builtins` と呼ばれています。)" #: ../../tutorial/classes.rst:106 msgid "" "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." msgstr "" "関数のローカルな名前空間は、関数が呼び出されたときに作成され、関数から戻った" "ときや、関数内で例外が送出され、かつ関数内で処理されなかった場合に削除されま" "す。 (実際には、忘れられる、と言ったほうが起きていることをよく表していま" "す。) もちろん、再帰呼出しのときには、各々の呼び出しで各自のローカルな名前空" "間があります。" #: ../../tutorial/classes.rst:112 msgid "" "A *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." msgstr "" "*スコープ (scope)* とは、ある名前空間が直接アクセスできるような、 Python プロ" "グラムのテキスト上の領域です。 \"直接アクセス可能\" とは、修飾なしに (訳注: " "``spam.egg`` ではなく単に ``egg`` のように) 名前を参照した際に、その名前空間" "から名前を見つけようと試みることを意味します。" #: ../../tutorial/classes.rst:116 msgid "" "Although scopes are determined statically, they are used dynamically. At any " "time during execution, there are 3 or 4 nested scopes whose namespaces are " "directly accessible:" msgstr "" "スコープは静的に決定されますが、動的に使用されます。実行中はいつでも、直接名" "前空間にアクセス可能な、3つまたは4つの入れ子になったスコープがあります:" #: ../../tutorial/classes.rst:120 msgid "the innermost scope, which is searched first, contains the local names" msgstr "最初に探される、最も内側のスコープは、ローカルな名前を持っています。" #: ../../tutorial/classes.rst:121 msgid "" "the scopes of any enclosing functions, which are searched starting with the " "nearest enclosing scope, contain non-local, but also non-global names" msgstr "" "外側の(enclosing)関数のスコープは、近いほうから順に探され、ローカルでもグロー" "バルでもない名前を持っています。" msgid "the next-to-last scope contains the current module's global names" msgstr "" "最後から 2 番目のスコープは現在のモジュールのグローバルな名前を持っています。" #: ../../tutorial/classes.rst:124 msgid "" "the outermost scope (searched last) is the namespace containing built-in " "names" msgstr "一番外側の(最後に検索される)スコープはビルトイン名を持っています。" msgid "" "If a name is declared global, then all references and assignments go " "directly to the next-to-last scope containing the module's global names. To " "rebind variables found outside of the innermost scope, the :keyword:" "`nonlocal` statement can be used; if not declared nonlocal, those variables " "are read-only (an attempt to write to such a variable will simply create a " "*new* local variable in the innermost scope, leaving the identically named " "outer variable unchanged)." msgstr "" "名前を global と宣言すると、その名前への参照と代入はすべて、モジュールのグ" "ローバル名を持つ最後から 2 番目のスコープで直接行われます。\n" "最も内側のスコープより外側にある変数を再束縛するには、:keyword:`nonlocal` 文" "を使えます。\n" "こうした外側の変数は、nonlocal と宣言しない限り読み出し専用です。\n" "代入しようとすると、最も内側のスコープに同名の *新しい* ローカル変数が作ら" "れ、外側の変数は変わりません。" #: ../../tutorial/classes.rst:133 msgid "" "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." msgstr "" "通常、ローカルスコープは (プログラムテキスト上の) 現在の関数のローカルな名前" "を参照します。関数の外側では、ローカルスコープはグローバルな名前空間と同じ名" "前空間、モジュールの名前空間を参照します。クラス定義では、ローカルスコープの" "中にもう一つ名前空間が置かれます。" #: ../../tutorial/classes.rst:138 msgid "" "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.)" msgstr "" "スコープはテキスト上で決定されていると理解することが重要です。モジュール内で" "定義される関数のグローバルなスコープは、関数がどこから呼び出されても、どんな" "別名をつけて呼び出されても、そのモジュールの名前空間になります。反対に、実際" "の名前の検索は実行時に動的に行われます --- とはいえ、言語の定義は、\"コンパイ" "ル\" 時の静的な名前解決の方向に進化しているので、動的な名前解決に頼ってはいけ" "ません! (事実、ローカルな変数は既に静的に決定されています。)" msgid "" "A special quirk of Python is that -- if no :keyword:`global` or :keyword:" "`nonlocal` statement is in effect -- assignments to names 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 ``del x`` removes " "the binding of ``x`` from the namespace referenced by the local scope. In " "fact, all operations that introduce new names use the local scope: in " "particular, :keyword:`import` statements and function definitions bind the " "module or function name in the local scope." msgstr "" ":keyword:`global` 文や :keyword:`nonlocal` 文が有効でない場合、\n" "Python では名前への代入は常に最も内側のスコープで行われます。\n" "代入はデータをコピーせず、名前をオブジェクトに束縛するだけです。\n" "削除も同様で、``del x`` はローカルスコープの名前空間から ``x`` の束縛を削除し" "ます。\n" "新しい名前を導入する操作はすべてローカルスコープを使います。\n" "例えば :keyword:`import` 文や関数定義は、モジュール名や関数名をローカルスコー" "プで束縛します。" #: ../../tutorial/classes.rst:154 msgid "" "The :keyword:`global` statement can be used to indicate that particular " "variables live in the global scope and should be rebound there; the :keyword:" "`nonlocal` statement indicates that particular variables live in an " "enclosing scope and should be rebound there." msgstr "" ":keyword:`global` 文を使うと、特定の変数がグローバルスコープに存在し、そこで" "再束縛されることを指示できます。 :keyword:`nonlocal` 文は、特定の変数が外側の" "スコープに存在し、そこで再束縛されることを指示します。" #: ../../tutorial/classes.rst:162 msgid "Scopes and Namespaces Example" msgstr "スコープと名前空間の例" #: ../../tutorial/classes.rst:164 msgid "" "This is an example demonstrating how to reference the different scopes and " "namespaces, and how :keyword:`global` and :keyword:`nonlocal` affect " "variable binding::" msgstr "" "異なるスコープと名前空間がどのように参照されるか、また :keyword:`global` およ" "び :keyword:`nonlocal` が変数の束縛にどう影響するか、この例で実演します::" #: ../../tutorial/classes.rst:168 msgid "" "def scope_test():\n" " def do_local():\n" " spam = \"local spam\"\n" "\n" " def do_nonlocal():\n" " nonlocal spam\n" " spam = \"nonlocal spam\"\n" "\n" " def do_global():\n" " global spam\n" " spam = \"global spam\"\n" "\n" " spam = \"test spam\"\n" " do_local()\n" " print(\"After local assignment:\", spam)\n" " do_nonlocal()\n" " print(\"After nonlocal assignment:\", spam)\n" " do_global()\n" " print(\"After global assignment:\", spam)\n" "\n" "scope_test()\n" "print(\"In global scope:\", spam)" msgstr "" "def scope_test():\n" " def do_local():\n" " spam = \"local spam\"\n" "\n" " def do_nonlocal():\n" " nonlocal spam\n" " spam = \"nonlocal spam\"\n" "\n" " def do_global():\n" " global spam\n" " spam = \"global spam\"\n" "\n" " spam = \"test spam\"\n" " do_local()\n" " print(\"After local assignment:\", spam)\n" " do_nonlocal()\n" " print(\"After nonlocal assignment:\", spam)\n" " do_global()\n" " print(\"After global assignment:\", spam)\n" "\n" "scope_test()\n" "print(\"In global scope:\", spam)" #: ../../tutorial/classes.rst:191 msgid "The output of the example code is:" msgstr "このコード例の出力は:" #: ../../tutorial/classes.rst:193 msgid "" "After local assignment: test spam\n" "After nonlocal assignment: nonlocal spam\n" "After global assignment: nonlocal spam\n" "In global scope: global spam" msgstr "" "After local assignment: test spam\n" "After nonlocal assignment: nonlocal spam\n" "After global assignment: nonlocal spam\n" "In global scope: global spam" #: ../../tutorial/classes.rst:200 msgid "" "Note how the *local* assignment (which is default) didn't change " "*scope_test*\\'s binding of *spam*. The :keyword:`nonlocal` assignment " "changed *scope_test*\\'s binding of *spam*, and the :keyword:`global` " "assignment changed the module-level binding." msgstr "" "このとおり、(デフォルトの) *ローカルな* 代入は *scope_test* 上の *spam* への" "束縛を変更しませんでした。 :keyword:`nonlocal` 代入は *scope_test* 上の " "*spam* への束縛を変更し、 :keyword:`global` 代入はモジュールレベルの束縛を変" "更しました。" msgid "" "You can also see that there was no previous binding for *spam* before the :" "keyword:`global` assignment." msgstr "" "また、:keyword:`global` による代入の前には、グローバルスコープで *spam* がま" "だ束縛されていなかったことも分かります。" #: ../../tutorial/classes.rst:212 msgid "A First Look at Classes" msgstr "クラス初見" #: ../../tutorial/classes.rst:214 msgid "" "Classes introduce a little bit of new syntax, three new object types, and " "some new semantics." msgstr "" "クラスでは、新しい構文を少しと、三つの新たなオブジェクト型、そして新たな意味" "付けをいくつか取り入れています。" #: ../../tutorial/classes.rst:221 msgid "Class Definition Syntax" msgstr "クラス定義の構文" #: ../../tutorial/classes.rst:223 msgid "The simplest form of class definition looks like this::" msgstr "クラス定義の最も単純な形式は、次のようになります::" #: ../../tutorial/classes.rst:225 msgid "" "class ClassName:\n" " \n" " .\n" " .\n" " .\n" " " msgstr "" "class ClassName:\n" " \n" " .\n" " .\n" " .\n" " " #: ../../tutorial/classes.rst:232 msgid "" "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.)" msgstr "" "関数定義 (:keyword:`def` 文) と同様、クラス定義が効果をもつにはまず実行しなけ" "ればなりません。 (クラス定義を :keyword:`if` 文の分岐先や関数内部に置くこと" "も、考え方としてはありえます。)" #: ../../tutorial/classes.rst:236 msgid "" "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." msgstr "" "実際には、クラス定義の内側にある文は、通常は関数定義になりますが、他の文を書" "くこともでき、それが役に立つこともあります --- これについては後で述べます。ク" "ラス内の関数定義は通常、メソッドの呼び出し規約で決められた独特の形式の引数リ" "ストを持ちます --- これについても後で述べます。" msgid "" "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." msgstr "" "クラス定義に入ると、新しい名前空間が作られ、ローカルスコープとして使われま" "す。\n" "したがって、ローカル変数への代入はすべてこの新しい名前空間に対して行われま" "す。\n" "特に、関数定義では新しい関数の名前がここに束縛されます。" #: ../../tutorial/classes.rst:247 msgid "" "When a class definition is left normally (via the end), a *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 definition 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)." msgstr "" "クラス定義から普通に (定義の終端に到達して) 抜けると、 *クラスオブジェクト " "(class object)* が生成されます。クラスオブジェクトは、基本的にはクラス定義で" "作成された名前空間の内容をくるむラッパー (wrapper) です。クラスオブジェクトに" "ついては次の節で詳しく学ぶことにします。 (クラス定義に入る前に有効だった) 元" "のローカルスコープが復帰し、生成されたクラスオブジェクトは復帰したローカルス" "コープにクラス定義のヘッダで指定した名前 (上の例では :class:`!ClassName`) で" "結び付けられます。" #: ../../tutorial/classes.rst:259 msgid "Class Objects" msgstr "クラスオブジェクト" #: ../../tutorial/classes.rst:261 msgid "" "Class objects support two kinds of operations: attribute references and " "instantiation." msgstr "" "クラスオブジェクトでは2種類の演算、属性参照とインスタンス生成をサポートして" "います。" #: ../../tutorial/classes.rst:264 msgid "" "*Attribute references* use the standard syntax used for all attribute " "references in Python: ``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::" msgstr "" "*属性参照 (attribute reference)* は、Python におけるすべての属性参照で使われ" "ている標準的な構文、 ``obj.name`` を使います。クラスオブジェクトが生成された" "際にクラスの名前空間にあった名前すべてが有効な属性名です。従って、以下のよう" "なクラス定義では::" #: ../../tutorial/classes.rst:269 msgid "" "class MyClass:\n" " \"\"\"A simple example class\"\"\"\n" " i = 12345\n" "\n" " def f(self):\n" " return 'hello world'" msgstr "" "class MyClass:\n" " \"\"\"A simple example class\"\"\"\n" " i = 12345\n" "\n" " def f(self):\n" " return 'hello world'" #: ../../tutorial/classes.rst:276 msgid "" "then ``MyClass.i`` and ``MyClass.f`` are valid attribute references, " "returning an integer and a function object, respectively. Class attributes " "can also be assigned to, so you can change the value of ``MyClass.i`` by " "assignment. :attr:`~type.__doc__` is also a valid attribute, returning the " "docstring belonging to the class: ``\"A simple example class\"``." msgstr "" "``MyClass.i`` と ``MyClass.f`` は有効な属性参照であり、それぞれ整数と関数オブ" "ジェクトを返します。クラス属性も代入できるため、代入により ``MyClass.i`` の値" "を変えられます。 :attr:`~type.__doc__` も有効な属性で、そのクラスに属している" "ドキュメンテーション文字列(docstring) 、この場合は ``\"A simple example " "class\"`` を返します。" #: ../../tutorial/classes.rst:282 msgid "" "Class *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)::" msgstr "" "クラスの *インスタンス化 (instantiation)* には関数記法を使います。クラスオブ" "ジェクトのことを、クラスの新しいインスタンスを返す、引数のない関数のように" "扱ってください。上記クラスで例示すると::" #: ../../tutorial/classes.rst:286 ../../tutorial/classes.rst:303 msgid "x = MyClass()" msgstr "x = MyClass()" #: ../../tutorial/classes.rst:288 msgid "" "creates a new *instance* of the class and assigns this object to the local " "variable ``x``." msgstr "" "は、クラスの新しい *インスタンス (instance)* を生成し、そのオブジェクトをロー" "カル変数 ``x`` へ代入します。" #: ../../tutorial/classes.rst:291 msgid "" "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 :" "meth:`~object.__init__`, like this::" msgstr "" "インスタンス化操作 (クラスオブジェクトの \"呼出し\") では、空のオブジェクトが" "作られます。多くのクラスでは、特定の初期状態にカスタマイズされたオブジェクト" "を作りたいです。そのために、クラスには :meth:`~object.__init__` という名前の" "特殊メソッドを定義できます。例えば次のようにします::" #: ../../tutorial/classes.rst:296 msgid "" "def __init__(self):\n" " self.data = []" msgstr "" "def __init__(self):\n" " self.data = []" #: ../../tutorial/classes.rst:299 msgid "" "When a class defines an :meth:`~object.__init__` method, class instantiation " "automatically invokes :meth:`!__init__` for the newly created class " "instance. So in this example, a new, initialized instance can be obtained " "by::" msgstr "" "クラスが :meth:`~object.__init__` メソッドを定義している場合、クラスをインス" "タンス化すると、新しく作られたクラスインスタンスに対して自動的に :meth:`!" "__init__` を呼び出します。 従って この例では、新たな初期済みインスタンスを次" "のようにして得られます::" #: ../../tutorial/classes.rst:305 msgid "" "Of course, the :meth:`~object.__init__` method may have arguments for " "greater flexibility. In that case, arguments given to the class " "instantiation operator are passed on to :meth:`!__init__`. For example, ::" msgstr "" "もちろん、より大きな柔軟性を持たせるために、 :meth:`~object.__init__` メソッ" "ドに複数の引数をもたせることができます。その場合、次の例のように、クラスのイ" "ンスタンス化操作に渡された引数は :meth:`!__init__` に渡されます。例えば、 ::" #: ../../tutorial/classes.rst:309 msgid "" ">>> class Complex:\n" "... def __init__(self, realpart, imagpart):\n" "... self.r = realpart\n" "... self.i = imagpart\n" "...\n" ">>> x = Complex(3.0, -4.5)\n" ">>> x.r, x.i\n" "(3.0, -4.5)" msgstr "" ">>> class Complex:\n" "... def __init__(self, realpart, imagpart):\n" "... self.r = realpart\n" "... self.i = imagpart\n" "...\n" ">>> x = Complex(3.0, -4.5)\n" ">>> x.r, x.i\n" "(3.0, -4.5)" #: ../../tutorial/classes.rst:322 msgid "Instance Objects" msgstr "インスタンスオブジェクト" #: ../../tutorial/classes.rst:324 msgid "" "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." msgstr "" "ところで、インスタンスオブジェクトを使うと何ができるのでしょうか?インスタン" "スオブジェクトが理解できる唯一の操作は、属性の参照です。有効な属性名には " "(データ属性およびメソッドの) 二種類あります。" msgid "" "*Data attributes* correspond to \"instance variables\" in Smalltalk, and to " "\"data members\" in C++. Data attributes need not be declared; like local " "variables, they spring into existence when they are first assigned to. For " "example, if ``x`` is the instance of :class:`!MyClass` created above, the " "following piece of code will print the value ``16``, without leaving a " "trace::" msgstr "" "*データ属性 (data attribute)* は Smalltalk の「インスタンス変数」や C++ の" "「データメンバ」に相当します。\n" "データ属性を宣言する必要はありません。\n" "ローカル変数と同様に、初めて値を代入したときに作られます。\n" "例えば、``x`` が上で作成した :class:`!MyClass` のインスタンスなら、\n" "次のコードは値 ``16`` を表示した後、追加した ``counter`` 属性を削除しま" "す。 ::" #: ../../tutorial/classes.rst:334 msgid "" "x.counter = 1\n" "while x.counter < 10:\n" " x.counter = x.counter * 2\n" "print(x.counter)\n" "del x.counter" msgstr "" "x.counter = 1\n" "while x.counter < 10:\n" " x.counter = x.counter * 2\n" "print(x.counter)\n" "del x.counter" #: ../../tutorial/classes.rst:340 msgid "" "The other kind of instance attribute reference is a *method*. A method is a " "function that \"belongs to\" an object." msgstr "" "もう一つのインスタンス属性の参照は、 *メソッド* です。メソッドとは、オブジェ" "クトに \"属する\" 関数のことです。" msgid "" "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, ``x.f`` is a " "valid method reference, since ``MyClass.f`` is a function, but ``x.i`` is " "not, since ``MyClass.i`` is not. But ``x.f`` is not the same thing as " "``MyClass.f`` --- it is a *method object*, not a function object." msgstr "" "インスタンスオブジェクトで有効なメソッド名は、そのクラスによって決まりま" "す。\n" "定義上、クラス属性が関数オブジェクトであれば、そのクラスのインスタンスに対応" "するメソッドが定義されます。\n" "この例では ``MyClass.f`` が関数なので、``x.f`` は有効なメソッド参照です。\n" "一方、``MyClass.i`` は関数ではないので、``x.i`` はメソッド参照ではありませ" "ん。\n" "ただし、``x.f`` は ``MyClass.f`` と同じものではありません。\n" "``x.f`` は関数オブジェクトではなく、*メソッドオブジェクト (method object)* で" "す。" #: ../../tutorial/classes.rst:356 msgid "Method Objects" msgstr "メソッドオブジェクト" #: ../../tutorial/classes.rst:358 msgid "Usually, a method is called right after it is bound::" msgstr "普通、メソッドはバインドされた直後に呼び出されます::" #: ../../tutorial/classes.rst:360 msgid "x.f()" msgstr "x.f()" #: ../../tutorial/classes.rst:362 msgid "" "If ``x = MyClass()``, as above, this will return the string ``'hello " "world'``. However, it is not necessary to call a method right away: ``x.f`` " "is a method object, and can be stored away and called at a later time. For " "example::" msgstr "" "もし ``x = MyClass()`` であれば、上記のコードは文字列 ``'hello world'`` を返" "すでしょう。しかしながら、必ずしもメソッドをその場で呼び出さなければならない" "わけではありません。 ``x.f`` はメソッドオブジェクトであり、どこかに記憶してお" "いて後で呼び出すことができます。例えば次のコードは::" #: ../../tutorial/classes.rst:366 msgid "" "xf = x.f\n" "while True:\n" " print(xf())" msgstr "" "xf = x.f\n" "while True:\n" " print(xf())" #: ../../tutorial/classes.rst:370 msgid "will continue to print ``hello world`` until the end of time." msgstr "``hello world`` を時が終わるまで印字し続けるでしょう。" #: ../../tutorial/classes.rst:372 msgid "" "What exactly happens when a method is called? You may have noticed that ``x." "f()`` was called without an argument above, even though the function " "definition for :meth:`!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..." msgstr "" "メソッドが呼び出されるときには実際には何が起きているのでしょうか? :meth:`!" "f` の関数定義では引数を一つ指定していたにもかかわらず、上の例では ``x.f()`` " "が引数なしで呼び出されています。引数はどうなったのでしょうか?たしか、引数が" "必要な関数を引数無しで呼び出すと、 Python が例外を送出するはずです --- たとえ" "その引数が実際には使われなくても…。" #: ../../tutorial/classes.rst:378 msgid "" "Actually, you may have guessed the answer: the special thing about methods " "is that the instance object is passed as the first argument of the " "function. In our example, the call ``x.f()`` is exactly equivalent to " "``MyClass.f(x)``. In general, calling a method with a list of *n* arguments " "is equivalent to calling the corresponding function with an argument list " "that is created by inserting the method's instance object before the first " "argument." msgstr "" "もう答は想像できているかもしれませんね:\n" "メソッドについて特別なこととして、インスタンスオブジェクトが関数の第1引数とし" "て渡されます。\n" "例では、 ``x.f()`` という呼び出しは、 ``MyClass.f(x)`` と厳密に等価なもので" "す。\n" "一般に、 *n* 個の引数リストもったメソッドの呼出しは、そのメソッドのインスタン" "スオブジェクトを最初の引数の前に挿入した引数リストで、メソッドに対応する関数" "を呼び出すことと等価です。" msgid "" "In general, methods work as follows. When a non-data attribute of an " "instance is referenced, the instance's class is searched. If the name " "denotes a valid class attribute that is a function object, references to " "both the instance object and the function object are packed into a method " "object. When the method object is called with an argument list, a new " "argument list is constructed from the instance object and the argument list, " "and the function object is called with this new argument list." msgstr "" "メソッドは一般に次のように動作します。\n" "インスタンスの非データ属性を参照すると、そのインスタンスのクラスから属性を探" "します。\n" "見つかった属性が関数オブジェクトなら、インスタンスと関数の両方への参照をまと" "めてメソッドオブジェクトにします。\n" "そのメソッドを呼び出すと、渡された引数の先頭にインスタンスを加えた新しい引数" "リストが作られます。\n" "そして、その引数リストで関数を呼び出します。" msgid "Class and Instance Variables" msgstr "クラス変数とインスタンス変数" #: ../../tutorial/classes.rst:400 msgid "" "Generally speaking, instance variables are for data unique to each instance " "and class variables are for attributes and methods shared by all instances " "of the class::" msgstr "" "一般的に、インスタンス変数はそれぞれのインスタンスについて固有のデータのため" "のもので、クラス変数はそのクラスのすべてのインスタンスによって共有される属性" "やメソッドのためのものです::" #: ../../tutorial/classes.rst:404 msgid "" "class Dog:\n" "\n" " kind = 'canine' # class variable shared by all instances\n" "\n" " def __init__(self, name):\n" " self.name = name # instance variable unique to each instance\n" "\n" ">>> d = Dog('Fido')\n" ">>> e = Dog('Buddy')\n" ">>> d.kind # shared by all dogs\n" "'canine'\n" ">>> e.kind # shared by all dogs\n" "'canine'\n" ">>> d.name # unique to d\n" "'Fido'\n" ">>> e.name # unique to e\n" "'Buddy'" msgstr "" "class Dog:\n" "\n" " kind = 'canine' # 全インスタンスで共有されるクラス変数\n" "\n" " def __init__(self, name):\n" " self.name = name # インスタンスごとに固有のインスタンス変数\n" "\n" ">>> d = Dog('Fido')\n" ">>> e = Dog('Buddy')\n" ">>> d.kind # すべての犬で共有\n" "'canine'\n" ">>> e.kind # すべての犬で共有\n" "'canine'\n" ">>> d.name # d 固有\n" "'Fido'\n" ">>> e.name # e 固有\n" "'Buddy'" #: ../../tutorial/classes.rst:422 msgid "" "As discussed in :ref:`tut-object`, shared data can have possibly surprising " "effects involving :term:`mutable` objects such as lists and dictionaries. " "For example, the *tricks* list in the following code should not be used as a " "class variable because just a single list would be shared by all *Dog* " "instances::" msgstr "" ":ref:`tut-object` で述べたように、共有データはリストや辞書のような :term:" "`mutable` オブジェクトで予期せぬ作用を生じることがあります。例えば、以下の" "コードの *tricks* リストはクラス変数として使われるべきではありません、なぜな" "ら単一のリストがすべての *Dog* インスタンスで共有されてしまうからです::" #: ../../tutorial/classes.rst:428 msgid "" "class Dog:\n" "\n" " tricks = [] # mistaken use of a class variable\n" "\n" " def __init__(self, name):\n" " self.name = name\n" "\n" " def add_trick(self, trick):\n" " self.tricks.append(trick)\n" "\n" ">>> d = Dog('Fido')\n" ">>> e = Dog('Buddy')\n" ">>> d.add_trick('roll over')\n" ">>> e.add_trick('play dead')\n" ">>> d.tricks # unexpectedly shared by all dogs\n" "['roll over', 'play dead']" msgstr "" "class Dog:\n" "\n" " tricks = [] # クラス変数の間違った使用\n" "\n" " def __init__(self, name):\n" " self.name = name\n" "\n" " def add_trick(self, trick):\n" " self.tricks.append(trick)\n" "\n" ">>> d = Dog('Fido')\n" ">>> e = Dog('Buddy')\n" ">>> d.add_trick('roll over')\n" ">>> e.add_trick('play dead')\n" ">>> d.tricks # 意図せず すべての犬で共有\n" "['roll over', 'play dead']" #: ../../tutorial/classes.rst:445 msgid "Correct design of the class should use an instance variable instead::" msgstr "このクラスの正しい設計ではインスタンス変数を代わりに使用するべきです::" #: ../../tutorial/classes.rst:447 msgid "" "class Dog:\n" "\n" " def __init__(self, name):\n" " self.name = name\n" " self.tricks = [] # creates a new empty list for each dog\n" "\n" " def add_trick(self, trick):\n" " self.tricks.append(trick)\n" "\n" ">>> d = Dog('Fido')\n" ">>> e = Dog('Buddy')\n" ">>> d.add_trick('roll over')\n" ">>> e.add_trick('play dead')\n" ">>> d.tricks\n" "['roll over']\n" ">>> e.tricks\n" "['play dead']" msgstr "" "class Dog:\n" "\n" " def __init__(self, name):\n" " self.name = name\n" " self.tricks = [] # 犬ごとに新しい空リストを作る\n" "\n" " def add_trick(self, trick):\n" " self.tricks.append(trick)\n" "\n" ">>> d = Dog('Fido')\n" ">>> e = Dog('Buddy')\n" ">>> d.add_trick('roll over')\n" ">>> e.add_trick('play dead')\n" ">>> d.tricks\n" "['roll over']\n" ">>> e.tricks\n" "['play dead']" #: ../../tutorial/classes.rst:469 msgid "Random Remarks" msgstr "いろいろな注意点" msgid "" "If the same attribute name occurs in both an instance and in a class, then " "attribute lookup prioritizes the instance::" msgstr "" "インスタンスとクラスに同じ名前の属性がある場合、属性の検索ではインスタンス側" "が優先されます。 ::" #: ../../tutorial/classes.rst:476 msgid "" ">>> class Warehouse:\n" "... purpose = 'storage'\n" "... region = 'west'\n" "...\n" ">>> w1 = Warehouse()\n" ">>> print(w1.purpose, w1.region)\n" "storage west\n" ">>> w2 = Warehouse()\n" ">>> w2.region = 'east'\n" ">>> print(w2.purpose, w2.region)\n" "storage east" msgstr "" ">>> class Warehouse:\n" "... purpose = 'storage'\n" "... region = 'west'\n" "...\n" ">>> w1 = Warehouse()\n" ">>> print(w1.purpose, w1.region)\n" "storage west\n" ">>> w2 = Warehouse()\n" ">>> w2.region = 'east'\n" ">>> print(w2.purpose, w2.region)\n" "storage east" msgid "" "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.)" msgstr "" "データ属性は、メソッドからも、オブジェクトの通常の利用者 (「クライアント」) " "からも参照できます。\n" "つまり、クラスを使って純粋な抽象データ型を実装することはできません。\n" "実際、Python にはデータの隠蔽を強制する仕組みがなく、すべて規約に基づいていま" "す。\n" "(一方、C で書かれた Python の実装では、必要に応じて実装の詳細を完全に隠し、オ" "ブジェクトへのアクセスを制御できます。\n" "C で書く Python の拡張ではこの仕組みを使えます。)" msgid "" "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." msgstr "" "クライアントはデータ属性を注意して使うべきです。\n" "データ属性を書き換えると、メソッドが維持する不変条件を壊す可能性がありま" "す。\n" "ただし、名前の衝突を避ければ、クライアントはメソッドの正常な動作に影響を与え" "ずに、インスタンスオブジェクトへ独自のデータ属性を追加できます。\n" "ここでも、名前付けの規約を使うと多くの問題を避けられます。" #: ../../tutorial/classes.rst:502 msgid "" "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." msgstr "" "メソッドの中から、データ属性を (または別のメソッドも!) 参照するための短縮さ" "れた記法はありません。私は、この仕様がメソッドの可読性を高めていると感じてい" "ます。あるメソッドを眺めているときにローカルな変数とインスタンス変数をはっき" "り区別できるからです。" msgid "" "Often, the first argument of a method is called ``self``. This is nothing " "more than a convention: the name ``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 *class browser* program might be written that relies upon such a " "convention." msgstr "" "メソッドの最初の引数は ``self`` と呼ぶことが多いです。\n" "これは単なる慣習であり、``self`` という名前自体は Python にとって特別な意味を" "持ちません。\n" "ただし、この慣習に従わないと、他の Python プログラマーにとってコードが読みに" "くくなる可能性があります。\n" "また、この慣習に依存する *クラスブラウザ (class browser)* プログラムが書かれ" "ることも考えられます。" #: ../../tutorial/classes.rst:513 msgid "" "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::" msgstr "" "クラス属性である関数オブジェクトはいずれも、そのクラスのインスタンスのための" "メソッドを定義しています。関数定義は、テキスト上でクラス定義の中に入っている" "必要はありません。関数オブジェクトをクラスのローカルな変数の中に代入するのも " "OK です。例えば以下のコードのようにします::" #: ../../tutorial/classes.rst:518 msgid "" "# Function defined outside the class\n" "def f1(self, x, y):\n" " return min(x, x+y)\n" "\n" "class C:\n" " f = f1\n" "\n" " def g(self):\n" " return 'hello world'\n" "\n" " h = g" msgstr "" "# クラス外で定義された関数\n" "def f1(self, x, y):\n" " return min(x, x+y)\n" "\n" "class C:\n" " f = f1\n" "\n" " def g(self):\n" " return 'hello world'\n" "\n" " h = g" #: ../../tutorial/classes.rst:530 msgid "" "Now ``f``, ``g`` and ``h`` are all attributes of class :class:`!C` that " "refer to function objects, and consequently they are all methods of " "instances of :class:`!C` --- ``h`` being exactly equivalent to ``g``. Note " "that this practice usually only serves to confuse the reader of a program." msgstr "" "これで、 ``f`` 、 ``g`` 、および ``h`` は、すべて :class:`!C` の属性であり関" "数オブジェクトを参照しています。従って、これらは、すべて :class:`!C` のインス" "タンスのメソッドとなります --- ``h`` は ``g`` と全く等価です。これを実践して" "も、大抵は単にプログラムの読者に混乱をもたらすだけなので注意してください。" #: ../../tutorial/classes.rst:535 msgid "" "Methods may call other methods by using method attributes of the ``self`` " "argument::" msgstr "" "メソッドは、 ``self`` 引数のメソッド属性を使って、他のメソッドを呼び出すこと" "ができます::" #: ../../tutorial/classes.rst:538 msgid "" "class Bag:\n" " def __init__(self):\n" " self.data = []\n" "\n" " def add(self, x):\n" " self.data.append(x)\n" "\n" " def addtwice(self, x):\n" " self.add(x)\n" " self.add(x)" msgstr "" "class Bag:\n" " def __init__(self):\n" " self.data = []\n" "\n" " def add(self, x):\n" " self.data.append(x)\n" "\n" " def addtwice(self, x):\n" " self.add(x)\n" " self.add(x)" msgid "" "Methods may reference global names in the same way as ordinary functions. " "The global scope associated with a method is the module containing its " "definition. (A class 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." msgstr "" "メソッドは通常の関数と同様にグローバル名を参照できます。\n" "メソッドのグローバルスコープは、その定義を含むモジュールです (クラスがグロー" "バルスコープになることはありません)。\n" "メソッドでグローバルデータを使う適切な理由はまれですが、グローバルスコープに" "は妥当な用途が数多くあります。\n" "例えば、グローバルスコープにインポートした関数やモジュール、そのスコープで定" "義した関数やクラスは、メソッドからも使えます。\n" "通常、そのメソッドを含むクラス自体もこのグローバルスコープで定義されていま" "す。\n" "次の節では、メソッドが自身のクラスを参照したくなる理由を見ていきます。" #: ../../tutorial/classes.rst:559 msgid "" "Each value is an object, and therefore has a *class* (also called its " "*type*). It is stored as ``object.__class__``." msgstr "" "個々の値はオブジェクトなので、 *クラス* (*型* とも言います) を持っています。" "それは ``object.__class__`` に保持されています。" #: ../../tutorial/classes.rst:566 msgid "Inheritance" msgstr "継承" #: ../../tutorial/classes.rst:568 msgid "" "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::" msgstr "" "言うまでもなく、継承の概念をサポートしない言語機能は \"クラス\" と呼ぶに値し" "ません。派生クラス (derived class) を定義する構文は次のようになります::" #: ../../tutorial/classes.rst:572 msgid "" "class DerivedClassName(BaseClassName):\n" " \n" " .\n" " .\n" " .\n" " " msgstr "" "class DerivedClassName(BaseClassName):\n" " \n" " .\n" " .\n" " .\n" " " #: ../../tutorial/classes.rst:579 msgid "" "The name :class:`!BaseClassName` must be defined in a namespace accessible " "from the scope containing the derived class definition. In place of a base " "class name, other arbitrary expressions are also allowed. This can be " "useful, for example, when the base class is defined in another module::" msgstr "" "基底クラス (base class) の名前 :class:`!BaseClassName` は、派生クラス定義の" "入っているスコープからアクセスできる名前空間で定義されていなければなりませ" "ん。基底クラス名のかわりに任意の式を入れることもできます。これは次の例のよう" "に、基底クラスが別モジュールで定義されているときに便利なことがあります::" #: ../../tutorial/classes.rst:585 msgid "class DerivedClassName(modname.BaseClassName):" msgstr "class DerivedClassName(modname.BaseClassName):" #: ../../tutorial/classes.rst:587 msgid "" "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, the search proceeds to look in the base class. This " "rule is applied recursively if the base class itself is derived from some " "other class." msgstr "" "派生クラス定義の実行は、基底クラスの場合と同じように進められます。クラスオブ" "ジェクトが構築される時、基底クラスが記憶されます。記憶された基底クラスは、属" "性参照を解決するために使われます。要求された属性がクラスに見つからなかった場" "合、基底クラスに検索が進みます。この規則は、基底クラスが他の何らかのクラスか" "ら派生したものであった場合、再帰的に適用されます。" #: ../../tutorial/classes.rst:593 msgid "" "There's nothing special about instantiation of derived classes: " "``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." msgstr "" "派生クラスのインスタンス化では、特別なことは何もありません。 " "``DerivedClassName()`` はクラスの新たなインスタンスを生成します。メソッドの参" "照は次のようにして解決されます。まず対応するクラス属性が検索されます。検索" "は、必要に応じ、基底クラス連鎖を下って行われ、検索の結果として何らかの関数オ" "ブジェクトがもたらされた場合、メソッド参照は有効なものとなります。" #: ../../tutorial/classes.rst:599 msgid "" "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 C++ programmers: all methods in Python are effectively ``virtual``.)" msgstr "" "派生クラスは基底クラスのメソッドを上書き (override) することができます。メ" "ソッドは同じオブジェクトの別のメソッドを呼び出す際に何ら特殊な権限を持ちませ" "ん。このため、ある基底クラスのメソッドが、同じ基底クラスで定義されているもう" "一つのメソッド呼び出しを行っている場合、派生クラスで上書きされた何らかのメ" "ソッドが呼び出されることになるかもしれません。 (C++ プログラマへ: Python で" "は、すべてのメソッドは事実上 ``virtual`` です。)" #: ../../tutorial/classes.rst:605 msgid "" "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 ``BaseClassName." "methodname(self, arguments)``. This is occasionally useful to clients as " "well. (Note that this only works if the base class is accessible as " "``BaseClassName`` in the global scope.)" msgstr "" "派生クラスで上書きしているメソッドでは、基底クラスの同名のメソッドを置き換え" "るのではなく、拡張したいのかもしれません。基底クラスのメソッドを直接呼び出す" "簡単な方法があります。単に ``BaseClassName.methodname(self, arguments)`` を呼" "び出すだけです。この仕様は、場合によってはクライアントでも役に立ちます。 (こ" "の呼び出し方が動作するのは、基底クラスがグローバルスコープの " "``BaseClassName`` という名前でアクセスできるときだけです。)" #: ../../tutorial/classes.rst:612 msgid "Python has two built-in functions that work with inheritance:" msgstr "Python には継承に関係する 2 つの組み込み関数があります:" #: ../../tutorial/classes.rst:614 msgid "" "Use :func:`isinstance` to check an instance's type: ``isinstance(obj, int)`` " "will be ``True`` only if ``obj.__class__`` is :class:`int` or some class " "derived from :class:`int`." msgstr "" ":func:`isinstance` を使うとインスタンスの型が調べられます。 " "``isinstance(obj, int)`` は ``obj.__class__`` が :class:`int` や :class:" "`int` の派生クラスの場合に限り ``True`` になります。" #: ../../tutorial/classes.rst:618 msgid "" "Use :func:`issubclass` to check class inheritance: ``issubclass(bool, int)`` " "is ``True`` since :class:`bool` is a subclass of :class:`int`. However, " "``issubclass(float, int)`` is ``False`` since :class:`float` is not a " "subclass of :class:`int`." msgstr "" ":func:`issubclass` を使うとクラスの継承関係が調べられます。 :class:`bool` " "は :class:`int` のサブクラスなので ``issubclass(bool, int)`` は ``True`` で" "す。しかし、 :class:`float` は :class:`int` のサブクラスではないので " "``issubclass(float, int)`` は ``False`` です。" #: ../../tutorial/classes.rst:628 msgid "Multiple Inheritance" msgstr "多重継承" #: ../../tutorial/classes.rst:630 msgid "" "Python supports a form of multiple inheritance as well. A class definition " "with multiple base classes looks like this::" msgstr "" "Python では、多重継承 (multiple inheritance) の形式もサポートしています。複数" "の基底クラスをもつクラス定義は次のようになります::" #: ../../tutorial/classes.rst:633 msgid "" "class DerivedClassName(Base1, Base2, Base3):\n" " \n" " .\n" " .\n" " .\n" " " msgstr "" "class DerivedClassName(Base1, Base2, Base3):\n" " \n" " .\n" " .\n" " .\n" " " #: ../../tutorial/classes.rst:640 msgid "" "For most purposes, in the simplest cases, you can think of the search for " "attributes inherited from a parent class as depth-first, left-to-right, not " "searching twice in the same class where there is an overlap in the " "hierarchy. Thus, if an attribute is not found in :class:`!DerivedClassName`, " "it is searched for in :class:`!Base1`, then (recursively) in the base " "classes of :class:`!Base1`, and if it was not found there, it was searched " "for in :class:`!Base2`, and so on." msgstr "" "ほとんどのシンプルな多重継承において、親クラスから継承される属性の検索は、深" "さ優先で、左から右に、そして継承の階層の中で同じクラスが複数出てくる(訳注: " "ダイアモンド継承と呼ばれます)場合に2度探索をしない、と考えることができま" "す。なので、ある属性が :class:`!DerivedClassName` で見つからない場合、まず :" "class:`!Base1` から検索され、そして(再帰的に) :class:`!Base1` の基底クラス" "から検索され、それでも見つからなかった場合は :class:`!Base2` から検索される、" "といった具合になります。" #: ../../tutorial/classes.rst:647 msgid "" "In fact, it is slightly more complex than that; the method resolution order " "changes dynamically to support cooperative calls to :func:`super`. This " "approach is known in some other multiple-inheritance languages as call-next-" "method and is more powerful than the super call found in single-inheritance " "languages." msgstr "" "実際には、それよりもう少しだけ複雑です。協調的な :func:`super` の呼び出しのた" "めにメソッドの解決順序は動的に変更されます。このアプローチは他の多重継承のあ" "る言語で call-next-method として知られており、単一継承しかない言語の super 呼" "び出しよりも強力です。" msgid "" "Dynamic ordering is necessary because all cases of multiple inheritance " "exhibit one or more diamond relationships (where at least one of the parent " "classes can be accessed through multiple paths from the bottommost class). " "For example, all classes inherit from :class:`object`, so any case of " "multiple inheritance provides more than one path to reach :class:`object`. " "To keep the base classes from being accessed more than once, the dynamic " "algorithm linearizes the search order in a way that preserves the left-to-" "right ordering specified in each class, that calls each parent only once, " "and that is monotonic (meaning that a class can be subclassed without " "affecting the precedence order of its parents). Taken together, these " "properties make it possible to design reliable and extensible classes with " "multiple inheritance. For more detail, see :ref:`python_2.3_mro`." msgstr "" "検索順序を動的に決める必要があるのは、どの多重継承にも 1 つ以上のダイヤモンド" "関係があるためです。\n" "これは、最も下位のクラスから同じ祖先クラスに複数の経路でたどり着ける関係を指" "します。\n" "例えば、すべてのクラスは :class:`object` を継承するので、多重継承では :class:" "`object` に至る経路が複数あります。\n" "同じ基底クラスを何度もたどらないように、動的なアルゴリズムで検索順序を一列に" "並べます。\n" "この順序は、各クラスで指定した基底クラスの左から右への順序を保ち、各祖先クラ" "スを一度だけたどるように決まります。\n" "さらに、サブクラスを作っても祖先クラス同士の優先順位が変わらない「単調性」を" "保ちます。\n" "こうした性質により、信頼性が高く拡張しやすい多重継承のクラスを設計できま" "す。\n" "詳しくは :ref:`python_2.3_mro` を参照してください。" #: ../../tutorial/classes.rst:666 msgid "" "In some cases multiple inheritance is not allowed; see :ref:`multiple-" "inheritance` for details." msgstr "" "いくつかの場合では多重継承が許されません。詳細は :ref:`multiple-inheritance` " "を見てください。" #: ../../tutorial/classes.rst:673 msgid "Private Variables" msgstr "プライベート変数" #: ../../tutorial/classes.rst:675 msgid "" "\"Private\" instance variables that cannot be accessed except from inside an " "object don't exist in Python. However, there is a convention that is " "followed by most Python code: a name prefixed with an underscore (e.g. " "``_spam``) should be treated as a non-public part of the API (whether it is " "a function, a method or a data member). It should be considered an " "implementation detail and subject to change without notice." msgstr "" "オブジェクトの中からしかアクセス出来ない \"プライベート\" インスタンス変数" "は、 Python にはありません。しかし、ほとんどの Python コードが従っている慣習" "があります。アンダースコアで始まる名前 (例えば ``_spam``) は、 (関数であれメ" "ソッドであれデータメンバであれ) 非 public なAPIとして扱います。これらは、予告" "なく変更されるかもしれない実装の詳細として扱われるべきです。" msgid "" "Since there is a valid use-case for class-private members (namely to avoid " "name clashes of names with names defined by subclasses), there is limited " "support for such a mechanism, called :dfn:`name mangling`. Any identifier " "of the form ``__spam`` (at least two leading underscores, at most one " "trailing underscore) is textually replaced with ``_classname__spam``, where " "``classname`` is the current class name with leading underscore(s) " "stripped. This mangling is done without regard to the syntactic position of " "the identifier, as long as it occurs within the definition of a class." msgstr "" "クラスのプライベートメンバは、サブクラスで定義された名前との衝突を避けるのに" "役立ちます。\n" "この用途のために、Python は名前マングリング (:dfn:`name mangling`) という限定" "的な仕組みを備えています。\n" "``__spam`` のように、先頭に 2 個以上、末尾に 1 個以下のアンダースコアを持つ識" "別子は、\n" "テキスト上で ``_classname__spam`` に置き換えられます。\n" "``classname`` は現在のクラス名から先頭のアンダースコアを取り除いたもので" "す。\n" "対象の識別子がクラス定義内にあれば、構文上の位置に関係なくこの変換が行われま" "す。" #: ../../tutorial/classes.rst:696 msgid "" "The :ref:`private name mangling specifications ` for " "details and special cases." msgstr "" "詳細と特例は、 :ref:`private name mangling specifications` 。" #: ../../tutorial/classes.rst:699 msgid "" "Name mangling is helpful for letting subclasses override methods without " "breaking intraclass method calls. For example::" msgstr "" "名前マングリングは、サブクラスが内部のメソッド呼び出しを壊さずにメソッドを" "オーバーライドするのに便利です。例えば::" #: ../../tutorial/classes.rst:702 msgid "" "class Mapping:\n" " def __init__(self, iterable):\n" " self.items_list = []\n" " self.__update(iterable)\n" "\n" " def update(self, iterable):\n" " for item in iterable:\n" " self.items_list.append(item)\n" "\n" " __update = update # private copy of original update() method\n" "\n" "class MappingSubclass(Mapping):\n" "\n" " def update(self, keys, values):\n" " # provides new signature for update()\n" " # but does not break __init__()\n" " for item in zip(keys, values):\n" " self.items_list.append(item)" msgstr "" "class Mapping:\n" " def __init__(self, iterable):\n" " self.items_list = []\n" " self.__update(iterable)\n" "\n" " def update(self, iterable):\n" " for item in iterable:\n" " self.items_list.append(item)\n" "\n" " __update = update # 元の update() メソッドのプライベートコピー\n" "\n" "class MappingSubclass(Mapping):\n" "\n" " def update(self, keys, values):\n" " # update() への新シグネチャ導入\n" " # しかし __init__() は壊さない\n" " for item in zip(keys, values):\n" " self.items_list.append(item)" #: ../../tutorial/classes.rst:721 msgid "" "The above example would work even if ``MappingSubclass`` were to introduce a " "``__update`` identifier since it is replaced with ``_Mapping__update`` in " "the ``Mapping`` class and ``_MappingSubclass__update`` in the " "``MappingSubclass`` class respectively." msgstr "" "上の例は、もし仮に ``MappingSubclass`` に ``__update`` 識別子を実装したとして" "もきちんと動きます。\n" "その理由は、 ``Mapping`` クラスではその識別子を ``_Mapping__update`` に、 " "``MappingSubclass`` クラスでは ``_MappingSubclass__update`` にそれぞれ置き換" "えるからです。" msgid "" "Note that the mangling rules are designed mostly to avoid accidents; it " "still is possible to access or modify a variable that is considered " "private. This can even be useful in special circumstances, such as in the " "debugger." msgstr "" "名前マングリングの主な目的は、名前の衝突などの事故を防ぐことです。\n" "プライベートとされている変数にも、アクセスしたり値を変更したりすることはでき" "ます。\n" "デバッガなどでは、この性質が役立つこともあります。" msgid "" "Notice that code passed to ``exec()`` or ``eval()`` does not consider the " "classname of the invoking class to be the current class; this is similar to " "the effect of the ``global`` statement, the effect of which is likewise " "restricted to code that is byte-compiled together. The same restriction " "applies to ``getattr()``, ``setattr()`` and ``delattr()``, as well as when " "referencing ``__dict__`` directly." msgstr "" "``exec()`` や ``eval()`` に渡したコードでは、呼び出し元のクラスは名前マングリ" "ングに使う現在のクラスとして扱われません。\n" "これは ``global`` 文と同様で、効果が及ぶのは一緒にバイトコンパイルされるコー" "ドの範囲だけです。\n" "``getattr()``、``setattr()``、``delattr()`` を使う場合や、``__dict__`` を直接" "参照する場合も同じ制約があります。" #: ../../tutorial/classes.rst:741 msgid "Odds and Ends" msgstr "残りのはしばし" msgid "" "Sometimes it is useful to have a data type similar to the Pascal \"record\" " "or C \"struct\", bundling together a few named data items. The idiomatic " "approach is to use :mod:`dataclasses` for this purpose::" msgstr "" "Pascal のレコードや C の構造体のように、名前付きのデータ項目をまとめる型があ" "ると便利なことがあります。\n" "Python では、この用途に :mod:`dataclasses` を使うのが一般的です。 ::" #: ../../tutorial/classes.rst:747 msgid "" "from dataclasses import dataclass\n" "\n" "@dataclass\n" "class Employee:\n" " name: str\n" " dept: str\n" " salary: int" msgstr "" "from dataclasses import dataclass\n" "\n" "@dataclass\n" "class Employee:\n" " name: str\n" " dept: str\n" " salary: int" #: ../../tutorial/classes.rst:757 msgid "" ">>> john = Employee('john', 'computer lab', 1000)\n" ">>> john.dept\n" "'computer lab'\n" ">>> john.salary\n" "1000" msgstr "" ">>> john = Employee('john', 'computer lab', 1000)\n" ">>> john.dept\n" "'computer lab'\n" ">>> john.salary\n" "1000" msgid "" "A piece of Python code that expects a particular abstract data type can " "often be passed a class that emulates the methods of that data type " "instead. For instance, if you have a function that formats some data from a " "file object, you can define a class with methods :meth:`~io.TextIOBase.read` " "and :meth:`~io.TextIOBase.readline` that get the data from a string buffer " "instead, and pass it as an argument." msgstr "" "特定の抽象データ型を想定した Python コードには、その型と同じように動くメソッ" "ドを備えたクラスを代わりに使えることがよくあります。\n" "例えば、ファイルオブジェクトから読み取ったデータをフォーマットする関数がある" "とします。\n" "ファイルの代わりに文字列バッファからデータを読み取る\n" ":meth:`~io.TextIOBase.read` と :meth:`~io.TextIOBase.readline` メソッドを持つ" "クラスを定義すれば、\n" "そのインスタンスをこの関数の引数として渡せます。" #: ../../tutorial/classes.rst:775 msgid "" ":ref:`Instance method objects ` have attributes, too: :" "attr:`m.__self__ ` is the instance object with the method :" "meth:`!m`, and :attr:`m.__func__ ` is the :ref:`function " "object ` corresponding to the method." msgstr "" ":ref:`Instance method objects ` にも属性があります。 :attr:" "`m.__self__ ` はメソッド :meth:`!m` の属しているインスタンス" "オブジェクトで、:attr:`m.__func__ ` はそのメソッドに対応す" "る :ref:`function object ` です。" #: ../../tutorial/classes.rst:785 msgid "Iterators" msgstr "イテレータ (iterator)" #: ../../tutorial/classes.rst:787 msgid "" "By now you have probably noticed that most container objects can be looped " "over using a :keyword:`for` statement::" msgstr "" "すでに気づいているでしょうが、 :keyword:`for` 文を使うとほとんどのコンテナオ" "ブジェクトにわたってループを行うことができます::" #: ../../tutorial/classes.rst:790 msgid "" "for element in [1, 2, 3]:\n" " print(element)\n" "for element in (1, 2, 3):\n" " print(element)\n" "for key in {'one':1, 'two':2}:\n" " print(key)\n" "for char in \"123\":\n" " print(char)\n" "for line in open(\"myfile.txt\"):\n" " print(line, end='')" msgstr "" "for element in [1, 2, 3]:\n" " print(element)\n" "for element in (1, 2, 3):\n" " print(element)\n" "for key in {'one':1, 'two':2}:\n" " print(key)\n" "for char in \"123\":\n" " print(char)\n" "for line in open(\"myfile.txt\"):\n" " print(line, end='')" #: ../../tutorial/classes.rst:801 msgid "" "This style of access is clear, concise, and convenient. The use of " "iterators pervades and unifies Python. Behind the scenes, the :keyword:" "`for` statement calls :func:`iter` on the container object. The function " "returns an iterator object that defines the method :meth:`~iterator." "__next__` which accesses elements in the container one at a time. When " "there are no more elements, :meth:`~iterator.__next__` raises a :exc:" "`StopIteration` exception which tells the :keyword:`!for` loop to " "terminate. You can call the :meth:`~iterator.__next__` method using the :" "func:`next` built-in function; this example shows how it all works::" msgstr "" "こういう要素へのアクセス方法は明確で簡潔で使い易いものです。イテレータの活用" "は Python へ広く行き渡り、統一感を持たせています。裏では :keyword:`!for` 文は" "コンテナオブジェクトに対して :func:`iter` 関数を呼んでいます。関数は、コンテ" "ナの中の要素に1つずつアクセスする :meth:`~iterator.__next__` メソッドが定義さ" "れているイテレータオブジェクトを返します。これ以上要素が無い場合は、 :meth:" "`~iterator.__next__` メソッドは :exc:`StopIteration` 例外を送出し、その通知を" "受け :keyword:`for` ループは終了します。組み込みの :func:`next` 関数を使っ" "て :meth:`~iterator.__next__` メソッドを直接呼ぶこともできます; この例は関数" "がどう働くのかを示しています::" #: ../../tutorial/classes.rst:810 msgid "" ">>> s = 'abc'\n" ">>> it = iter(s)\n" ">>> it\n" "\n" ">>> next(it)\n" "'a'\n" ">>> next(it)\n" "'b'\n" ">>> next(it)\n" "'c'\n" ">>> next(it)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" " next(it)\n" "StopIteration" msgstr "" ">>> s = 'abc'\n" ">>> it = iter(s)\n" ">>> it\n" "\n" ">>> next(it)\n" "'a'\n" ">>> next(it)\n" "'b'\n" ">>> next(it)\n" "'c'\n" ">>> next(it)\n" "Traceback (most recent call last):\n" " File \"\", line 1, in \n" " next(it)\n" "StopIteration" #: ../../tutorial/classes.rst:826 msgid "" "Having seen the mechanics behind the iterator protocol, it is easy to add " "iterator behavior to your classes. Define an :meth:`~container.__iter__` " "method which returns an object with a :meth:`~iterator.__next__` method. If " "the class defines :meth:`!__next__`, then :meth:`!__iter__` can just return " "``self``::" msgstr "" "イテレータプロトコルの裏にある仕組みを観察していれば、自作のクラスにイテレー" "タとしての振舞いを追加するのは簡単です。 :meth:`~iterator.__next__` メソッド" "を持つオブジェクトを返す :meth:`~container.__iter__` メソッドを定義するので" "す。クラスが :meth:`!__next__` メソッドを定義している場合、 :meth:`!" "__iter__` メソッドは単に ``self`` を返すことも可能です::" #: ../../tutorial/classes.rst:831 msgid "" "class Reverse:\n" " \"\"\"Iterator for looping over a sequence backwards.\"\"\"\n" " def __init__(self, data):\n" " self.data = data\n" " self.index = len(data)\n" "\n" " def __iter__(self):\n" " return self\n" "\n" " def __next__(self):\n" " if self.index == 0:\n" " raise StopIteration\n" " self.index = self.index - 1\n" " return self.data[self.index]" msgstr "" "class Reverse:\n" " \"\"\"シーケンスを後ろからまわるイテレータ.\"\"\"\n" " def __init__(self, data):\n" " self.data = data\n" " self.index = len(data)\n" "\n" " def __iter__(self):\n" " return self\n" "\n" " def __next__(self):\n" " if self.index == 0:\n" " raise StopIteration\n" " self.index = self.index - 1\n" " return self.data[self.index]" #: ../../tutorial/classes.rst:848 msgid "" ">>> rev = Reverse('spam')\n" ">>> iter(rev)\n" "<__main__.Reverse object at 0x00A1DB50>\n" ">>> for char in rev:\n" "... print(char)\n" "...\n" "m\n" "a\n" "p\n" "s" msgstr "" ">>> rev = Reverse('spam')\n" ">>> iter(rev)\n" "<__main__.Reverse object at 0x00A1DB50>\n" ">>> for char in rev:\n" "... print(char)\n" "...\n" "m\n" "a\n" "p\n" "s" #: ../../tutorial/classes.rst:863 msgid "Generators" msgstr "ジェネレータ (generator)" #: ../../tutorial/classes.rst:865 msgid "" ":term:`Generators ` are a simple and powerful tool for creating " "iterators. They are written like regular functions but use the :keyword:" "`yield` statement whenever they want to return data. Each time :func:`next` " "is called on it, the generator resumes where it left off (it remembers all " "the data values and which statement was last executed). An example shows " "that generators can be trivially easy to create::" msgstr "" ":term:`ジェネレータ ` は、イテレータを作成するための簡潔で強力な" "ツールです。ジェネレータは通常の関数のように書かれますが、何らかのデータを返" "すときには :keyword:`yield` 文を使います。そのジェネレータに対して :func:" "`next` が呼び出されるたびに、ジェネレータは以前に中断した処理を再開します " "(ジェネレータは、全てのデータ値と最後にどの文が実行されたかを記憶していま" "す)。以下の例を見れば、ジェネレータがとても簡単に作成できることがわかります::" #: ../../tutorial/classes.rst:872 msgid "" "def reverse(data):\n" " for index in range(len(data)-1, -1, -1):\n" " yield data[index]" msgstr "" "def reverse(data):\n" " for index in range(len(data)-1, -1, -1):\n" " yield data[index]" #: ../../tutorial/classes.rst:878 msgid "" ">>> for char in reverse('golf'):\n" "... print(char)\n" "...\n" "f\n" "l\n" "o\n" "g" msgstr "" ">>> for char in reverse('golf'):\n" "... print(char)\n" "...\n" "f\n" "l\n" "o\n" "g" #: ../../tutorial/classes.rst:886 msgid "" "Anything that can be done with generators can also be done with class-based " "iterators as described in the previous section. What makes generators so " "compact is that the :meth:`~iterator.__iter__` and :meth:`~generator." "__next__` methods are created automatically." msgstr "" "ジェネレータでできることは、前の節で解説したクラスを使ったイテレータでも実現" "できます。ジェネレータの定義がコンパクトになるのは :meth:`~iterator." "__iter__` メソッドと :meth:`~generator.__next__` メソッドが自動で作成されるか" "らです。" msgid "" "Another key feature is that the local variables and execution state are " "automatically saved between calls. This made the function easier to write " "and much more clear than an approach using instance variables like ``self." "index`` and ``self.data``." msgstr "" "もう一つの重要な機能は、呼び出しと呼び出しの間にローカル変数と実行状態が自動" "的に保存されることです。\n" "このため、``self.index`` や ``self.data`` のようなインスタンス変数を使う方法" "よりも、関数を簡単に書け、コードもずっと明確になります。" #: ../../tutorial/classes.rst:896 msgid "" "In addition to automatic method creation and saving program state, when " "generators terminate, they automatically raise :exc:`StopIteration`. In " "combination, these features make it easy to create iterators with no more " "effort than writing a regular function." msgstr "" "メソッドを自動生成したりプログラムの実行状態を自動保存するほかに、ジェネレー" "タは終了時に自動的に :exc:`StopIteration` を送出します。これらの機能を組み合" "わせると、通常の関数を書くのと同じ労力で、簡単にイテレータを生成できます。" #: ../../tutorial/classes.rst:905 msgid "Generator Expressions" msgstr "ジェネレータ式" msgid "" "Some simple generators can be coded succinctly as expressions using a syntax " "similar to list comprehensions but with parentheses instead of square " "brackets. These expressions are designed for situations where the generator " "is used right away by an enclosing function. Generator expressions are more " "compact but less versatile than full generator definitions and tend to be " "more memory friendly than equivalent list comprehensions." msgstr "" "単純なジェネレータは、リスト内包表記の角括弧を丸括弧に替えたような構文で、短" "い式として書けます。\n" "このジェネレータ式は、ジェネレータを関数の引数として渡し、その関数ですぐに使" "う場合に適しています。\n" "ジェネレータを関数として定義するより用途は限られますが、短く書けます。\n" "また、同じ内容のリスト内包表記よりメモリ使用量を抑えられることが多くなりま" "す。" #: ../../tutorial/classes.rst:914 msgid "Examples::" msgstr "例::" #: ../../tutorial/classes.rst:916 msgid "" ">>> sum(i*i for i in range(10)) # sum of squares\n" "285\n" "\n" ">>> xvec = [10, 20, 30]\n" ">>> yvec = [7, 5, 3]\n" ">>> sum(x*y for x,y in zip(xvec, yvec)) # dot product\n" "260\n" "\n" ">>> unique_words = set(word for line in page for word in line.split())\n" "\n" ">>> valedictorian = max((student.gpa, student.name) for student in " "graduates)\n" "\n" ">>> data = 'golf'\n" ">>> list(data[i] for i in range(len(data)-1, -1, -1))\n" "['f', 'l', 'o', 'g']\n" "\n" ">>> x = [[1,2,3], [], [4, 5]]\n" ">>> g = (*i for i in x)\n" ">>> list(g)\n" "[1, 2, 3, 4, 5]" msgstr "" ">>> sum(i*i for i in range(10)) # 平方和\n" "285\n" "\n" ">>> xvec = [10, 20, 30]\n" ">>> yvec = [7, 5, 3]\n" ">>> sum(x*y for x,y in zip(xvec, yvec)) # ドット積\n" "260\n" "\n" ">>> unique_words = set(word for line in page for word in line.split())\n" "\n" ">>> valedictorian = max((student.gpa, student.name) for student in " "graduates)\n" "\n" ">>> data = 'golf'\n" ">>> list(data[i] for i in range(len(data)-1, -1, -1))\n" "['f', 'l', 'o', 'g']\n" "\n" ">>> x = [[1,2,3], [], [4, 5]]\n" ">>> g = (*i for i in x)\n" ">>> list(g)\n" "[1, 2, 3, 4, 5]" #: ../../tutorial/classes.rst:937 msgid "" "In most cases, generator expressions must be wrapped in parentheses. As a " "special case, however, when provided as the sole argument to a function (as " "in the examples involving ``sum``, ``set``, ``max``, and ``list`` above), " "the generator expression does not need to be wrapped in an additional set of " "parentheses. That is to say, the following two pieces of code are " "semantically equivalent::" msgstr "" "多くの場合、ジェネレータ式は括弧で囲む必要があります。 ただし特例として、唯" "一の実引数として関数に渡す場合(前述の ``sum``, ``set``, ``max``, ``list`` の" "例のように)は、ジェネレータ式を追加の括弧で囲む必要がありません。 すなわ" "ち、次の2つのコード片は意味的に等価です::" #: ../../tutorial/classes.rst:944 msgid "" ">>> f(x for x in y)\n" ">>> f((x for x in y))" msgstr "" ">>> f(x for x in y)\n" ">>> f((x for x in y))" #: ../../tutorial/classes.rst:947 msgid "as are the following::" msgstr "以下も同様です::" #: ../../tutorial/classes.rst:949 msgid "" ">>> f(*x for x in y)\n" ">>> f((*x for x in y))" msgstr "" ">>> f(*x for x in y)\n" ">>> f((*x for x in y))" #: ../../tutorial/classes.rst:954 msgid "Footnotes" msgstr "脚注" #: ../../tutorial/classes.rst:955 msgid "" "Except for one thing. Module objects have a secret read-only attribute " "called :attr:`~object.__dict__` which returns the dictionary used to " "implement the module's namespace; the name ``__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." msgstr "" "例外が一つあります。モジュールオブジェクトには、秘密の読取り専用の属性 :attr:" "`~object.__dict__` があり、モジュールの名前空間を実装するために使われている辞" "書を返します; ``__dict__`` という名前は属性ですが、グローバルな名前ではありま" "せん。この属性を利用すると名前空間の実装に対する抽象化を侵すことになるので、" "プログラムを検死するデバッガのような用途に限るべきです。" #: ../../tutorial/classes.rst:343 msgid "object" msgstr "object" #: ../../tutorial/classes.rst:343 msgid "method" msgstr "メソッド" #: ../../tutorial/classes.rst:682 msgid "name" msgstr "name" msgid "mangling" msgstr "マングリング"