# SOME DESCRIPTIVE TITLE. # Copyright (C) 2001-2022, Python Software Foundation # This file is distributed under the same license as the Python package. # FIRST AUTHOR , YEAR. # # Translators: # Rafael Fontenelle , 2022 # #, fuzzy msgid "" msgstr "" "Project-Id-Version: Python 3.10\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2022-12-30 14:59+0000\n" "PO-Revision-Date: 2022-11-05 17:21+0000\n" "Last-Translator: Rafael Fontenelle , 2022\n" "Language-Team: Japanese (https://www.transifex.com/python-doc/teams/5390/" "ja/)\n" "Language: ja\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=1; plural=0;\n" #: ../../faq/programming.rst:5 msgid "Programming FAQ" msgstr "プログラミング FAQ" #: ../../faq/programming.rst:8 msgid "Contents" msgstr "内容" #: ../../faq/programming.rst:12 msgid "General Questions" msgstr "一般的な質問" #: ../../faq/programming.rst:15 msgid "" "Is there a source code level debugger with breakpoints, single-stepping, " "etc.?" msgstr "" "ブレークポイントやシングルステップ実行などを備えたソースコードレベルデバッガ" "はありますか?" #: ../../faq/programming.rst:17 ../../faq/programming.rst:58 msgid "Yes." msgstr "はい。" #: ../../faq/programming.rst:19 msgid "" "Several debuggers for Python are described below, and the built-in function :" "func:`breakpoint` allows you to drop into any of them." msgstr "" "Python 用のデバッガについては次に解説してあり、組み込みの :func:`breakpoint` " "関数でそれらのデバッガに処理を移せます。" #: ../../faq/programming.rst:22 msgid "" "The pdb module is a simple but adequate console-mode debugger for Python. It " "is part of the standard Python library, and is :mod:`documented in the " "Library Reference Manual `. You can also write your own debugger by " "using the code for pdb as an example." msgstr "" "pdb モジュールは簡素にして十分な Python のコンソールモードデバッガです。これ" "は Python の標準ライブラリに含まれているもので、 :mod:`ライブラリリファレンス" "マニュアルにドキュメントがあります ` 。 pdb のコードを手本にして自分用の" "デバッガを書くこともできます。" #: ../../faq/programming.rst:27 msgid "" "The IDLE interactive development environment, which is part of the standard " "Python distribution (normally available as `Tools/scripts/idle3 `_), includes a " "graphical debugger." msgstr "" "Python に同梱されている統合開発環境の IDLE は通常の Python の配布形態の一部 " "(普通は `Tools/scripts/idle3 `_ から利用可能) であり、グラフィカルなデバッガを含んでい" "ます。" #: ../../faq/programming.rst:32 msgid "" "PythonWin is a Python IDE that includes a GUI debugger based on pdb. The " "PythonWin debugger colors breakpoints and has quite a few cool features such " "as debugging non-PythonWin programs. PythonWin is available as part of " "`pywin32 `_ project and as a part of " "the `ActivePython `_ " "distribution." msgstr "" "PythonWin は、pdb をベースとした GUI デバッガを含む Python IDE です。" "Pythonwin デバッガは、ブレークポイントの色付けや非 PythonWin プログラムのデ" "バッグなどの素敵な機能をたくさん持っています。PythonWin は `pywin32 " "`_ プロジェクトの一部、あるいは " "`ActivePython `_ ディストリ" "ビューションの一部として利用可能です。" #: ../../faq/programming.rst:39 msgid "" "`Eric `_ is an IDE built on PyQt and " "the Scintilla editing component." msgstr "" "`Eric `_ は PyQt や Scintilla editing " "component をもとにした IDE です。" #: ../../faq/programming.rst:42 msgid "" "`trepan3k `_ is a gdb-like " "debugger." msgstr "" "`trepan3k `_ は gdbライクなデバッガ" "です。" #: ../../faq/programming.rst:44 msgid "" "`Visual Studio Code `_ is an IDE with " "debugging tools that integrates with version-control software." msgstr "" "`Visual Studio Code `_ はバージョン管理ソフト" "と一緒になったデバッグツールを備えた IDE です" #: ../../faq/programming.rst:47 msgid "" "There are a number of commercial Python IDEs that include graphical " "debuggers. They include:" msgstr "商業のグラフィカルデバッガ付き Python IDE もあります。例えば:" #: ../../faq/programming.rst:50 msgid "`Wing IDE `_" msgstr "`Wing IDE `_" #: ../../faq/programming.rst:51 msgid "`Komodo IDE `_" msgstr "`Komodo IDE `_" #: ../../faq/programming.rst:52 msgid "`PyCharm `_" msgstr "`PyCharm `_" #: ../../faq/programming.rst:56 msgid "Are there tools to help find bugs or perform static analysis?" msgstr "バグの発見や静的解析に役立つツールはありますか?" #: ../../faq/programming.rst:60 msgid "" "`Pylint `_ and `Pyflakes " "`_ do basic checking that will help you " "catch bugs sooner." msgstr "" "`Pylint `_ と `Pyflakes " "`_ は、バグの早期発見に役立つ基本的な" "チェックを行います。" #: ../../faq/programming.rst:64 msgid "" "Static type checkers such as `Mypy `_, `Pyre `_, and `Pytype `_ can " "check type hints in Python source code." msgstr "" "`Mypy `_, `Pyre `_, `Pytype " "`_ などの静的型チェッカーは、 Python ソース" "コードにある型ヒントをチェックできます。" #: ../../faq/programming.rst:73 msgid "How can I create a stand-alone binary from a Python script?" msgstr "どうしたら Python スクリプトからスタンドアロンバイナリを作れますか?" #: ../../faq/programming.rst:75 msgid "" "You don't need the ability to compile Python to C code if all you want is a " "stand-alone program that users can download and run without having to " "install the Python distribution first. There are a number of tools that " "determine the set of modules required by a program and bind these modules " "together with a Python binary to produce a single executable." msgstr "" "ユーザがダウンロードでき、Python ディストリビューションをインストールせずに実" "行できるようなスタンドアロンプログラムだけでいいなら、Python を C コードにコ" "ンパイルできなくても構いません。プログラムに対して必要なモジュールを選び、そ" "のモジュールを Python バイナリに束縛して一つの実行可能ファイルにまとめる多く" "のツールがあります。" #: ../../faq/programming.rst:81 msgid "" "One is to use the freeze tool, which is included in the Python source tree " "as `Tools/freeze `_. It converts Python byte code to C arrays; with a C compiler you " "can embed all your modules into a new program, which is then linked with the " "standard Python modules." msgstr "" "一つは freeze ツールで、Python ソースツリーに `Tools/freeze `_ として含まれています。これは " "Python バイトコードを C 配列に変換します。すべてのモジュールを新しいプログラ" "ムに埋め込む C コンパイラで、そのプログラムは Python モジュールにリンクされま" "す。" #: ../../faq/programming.rst:87 msgid "" "It works by scanning your source recursively for import statements (in both " "forms) and looking for the modules in the standard Python path as well as in " "the source directory (for built-in modules). It then turns the bytecode for " "modules written in Python into C code (array initializers that can be turned " "into code objects using the marshal module) and creates a custom-made config " "file that only contains those built-in modules which are actually used in " "the program. It then compiles the generated C code and links it with the " "rest of the Python interpreter to form a self-contained binary which acts " "exactly like your script." msgstr "" "これはあなたのソースの (両方の形式の) import 文を再帰的にスキャンし、import " "されたモジュールを標準の Python パスと (組み込みモジュールのある) ソースディ" "レクトリから探します。そして Python で書かれたモジュールのバイトコードを C " "コード (marshal モジュールでコードオブジェクトに変換できる配列) に変換し、実" "際にそのプログラム内で使われている組み込みモジュールだけが含まれたカスタムメ" "イドの設定ファイルを作成します。そして生成された C コードをコンパイルして " "Python インタプリタの残りとリンクし、元のスクリプトと全く同じように動作する自" "己完結的なバイナリを形成します。" #: ../../faq/programming.rst:96 msgid "" "The following packages can help with the creation of console and GUI " "executables:" msgstr "以下のパッケージはコンソールやGUIの実行ファイル作成に役立ちます。" #: ../../faq/programming.rst:99 msgid "`Nuitka `_ (Cross-platform)" msgstr "`Nuitka `_ (Cross-platform)" #: ../../faq/programming.rst:100 msgid "`PyInstaller `_ (Cross-platform)" msgstr "`PyInstaller `_ (Cross-platform)" #: ../../faq/programming.rst:101 msgid "" "`PyOxidizer `_ (Cross-platform)" msgstr "" "`PyOxidizer `_ (Cross-platform)" #: ../../faq/programming.rst:102 msgid "" "`cx_Freeze `_ (Cross-platform)" msgstr "" "`cx_Freeze `_ (Cross-platform)" #: ../../faq/programming.rst:103 msgid "`py2app `_ (macOS only)" msgstr "`py2app `_ (macOS only)" #: ../../faq/programming.rst:104 msgid "`py2exe `_ (Windows only)" msgstr "`py2exe `_ (Windows only)" #: ../../faq/programming.rst:107 msgid "Are there coding standards or a style guide for Python programs?" msgstr "" "Python プログラムのためのコーディングスタンダードやスタイルガイドはあります" "か?" #: ../../faq/programming.rst:109 msgid "" "Yes. The coding style required for standard library modules is documented " "as :pep:`8`." msgstr "" "はい。標準ライブラリモジュールに求められるコーディングスタイルは :pep:`8` と" "して文書化されています。" #: ../../faq/programming.rst:114 msgid "Core Language" msgstr "コア言語" #: ../../faq/programming.rst:119 msgid "Why am I getting an UnboundLocalError when the variable has a value?" msgstr "なぜ変数に値があるのに UnboundLocalError が出るのですか?" #: ../../faq/programming.rst:121 msgid "" "It can be a surprise to get the :exc:`UnboundLocalError` in previously " "working code when it is modified by adding an assignment statement somewhere " "in the body of a function." msgstr "" "もともと動いていたコードが、関数の本体のどこかに代入文を加えるという変更をし" "たら :exc:`UnboundLocalError` を出すのには驚くかもしれません。" #: ../../faq/programming.rst:125 msgid "This code:" msgstr "このコード:" #: ../../faq/programming.rst:134 msgid "works, but this code:" msgstr "は動きますが、このコード:" #: ../../faq/programming.rst:141 msgid "results in an :exc:`!UnboundLocalError`:" msgstr "は :exc:`!UnboundLocalError` になります:" #: ../../faq/programming.rst:148 msgid "" "This is because when you make an assignment to a variable in a scope, that " "variable becomes local to that scope and shadows any similarly named " "variable in the outer scope. Since the last statement in foo assigns a new " "value to ``x``, the compiler recognizes it as a local variable. " "Consequently when the earlier ``print(x)`` attempts to print the " "uninitialized local variable and an error results." msgstr "" "これは、あるスコープの中で変数に代入を行うとき、その変数はそのスコープに対し" "てローカルになり、外のスコープにある同じ名前の変数を隠すからです。foo の最後" "の文が ``x`` に新しい値を代入しているので、コンパイラはこれをローカル変数であ" "ると認識します。その結果、先の ``print(x)`` が初期化されていないローカル変数" "を表示しようとして結果はエラーとなります。" #: ../../faq/programming.rst:155 msgid "" "In the example above you can access the outer scope variable by declaring it " "global:" msgstr "" "上の例では、グローバルであると宣言することで外のスコープにアクセスできます:" #: ../../faq/programming.rst:167 msgid "" "This explicit declaration is required in order to remind you that (unlike " "the superficially analogous situation with class and instance variables) you " "are actually modifying the value of the variable in the outer scope:" msgstr "" "この明示的な宣言は (表面的には似ているクラスとインスタンス変数の例とは違っ" "て) あなたは実際は他のスコープの変数の値を変えようとしているのだ、ということ" "を知らせるのに必要です:" #: ../../faq/programming.rst:174 msgid "" "You can do a similar thing in a nested scope using the :keyword:`nonlocal` " "keyword:" msgstr "" "同様のことを、ネストされたスコープで :keyword:`nonlocal` 予約語を使うことでも" "できます:" #: ../../faq/programming.rst:192 msgid "What are the rules for local and global variables in Python?" msgstr "Python のローカルとグローバル変数のルールは何ですか?" #: ../../faq/programming.rst:194 msgid "" "In Python, variables that are only referenced inside a function are " "implicitly global. If a variable is assigned a value anywhere within the " "function's body, it's assumed to be a local unless explicitly declared as " "global." msgstr "" "Python では、関数内で参照されるだけの変数は暗黙的にグローバルとなります。\n" "関数の本体のどこかで値が変数に代入されたなら、それは明示的にグローバルである" "と宣言されない限り、ローカルであるとみなされます。" #: ../../faq/programming.rst:198 msgid "" "Though a bit surprising at first, a moment's consideration explains this. " "On one hand, requiring :keyword:`global` for assigned variables provides a " "bar against unintended side-effects. On the other hand, if ``global`` was " "required for all global references, you'd be using ``global`` all the time. " "You'd have to declare as global every reference to a built-in function or to " "a component of an imported module. This clutter would defeat the usefulness " "of the ``global`` declaration for identifying side-effects." msgstr "" "最初はちょっと驚くでしょうが、少し考えると納得できます。一方では、代入された" "変数に :keyword:`global` を要求することで、意図しない副作用を防げます。他方で" "は、グローバルな参照の度に ``global`` が要求されてしまうと、 ``global`` を" "使ってばかりになってしまいます。ビルトイン関数やインポートされたモジュールの" "内容を参照するたびにグローバル宣言をしなければならないのです。その乱雑さは副" "作用を特定するための ``global`` 宣言の便利さよりも重大です。" #: ../../faq/programming.rst:208 msgid "" "Why do lambdas defined in a loop with different values all return the same " "result?" msgstr "" "ループの中で異なる値で定義されたラムダ式が、同じ値を返すのはなぜですか?" #: ../../faq/programming.rst:210 msgid "" "Assume you use a for loop to define a few different lambdas (or even plain " "functions), e.g.::" msgstr "" "for ループを使って、少しずつ異なるラムダを定義 (もしくは簡単な関数) するとし" "ます。例えば::" #: ../../faq/programming.rst:217 msgid "" "This gives you a list that contains 5 lambdas that calculate ``x**2``. You " "might expect that, when called, they would return, respectively, ``0``, " "``1``, ``4``, ``9``, and ``16``. However, when you actually try you will " "see that they all return ``16``::" msgstr "" "これで ``x**2`` を計算する 5 つのラムダのリストが得られます。それらを呼び出し" "たとき、それぞれ ``0``、``1``、``4``、``9``、``16`` を返すと予想するかもしれ" "ません。しかし実際にやってみると、全て ``16`` が返ってくるのを目にするでしょ" "う::" #: ../../faq/programming.rst:227 msgid "" "This happens because ``x`` is not local to the lambdas, but is defined in " "the outer scope, and it is accessed when the lambda is called --- not when " "it is defined. At the end of the loop, the value of ``x`` is ``4``, so all " "the functions now return ``4**2``, i.e. ``16``. You can also verify this by " "changing the value of ``x`` and see how the results of the lambdas change::" msgstr "" "これは、``x`` がラムダにとってのローカル変数ではなく外側のスコープで定義され" "ていて、ラムダが定義されたときでなく呼び出されたときにアクセスされるために起" "こります。ループが終わった時点では ``x`` は ``4`` であり、従って、全ての関数" "は ``4**2`` つまり ``16`` を返します。このことは ``x`` の値を変えてみることで" "検証でき、ラムダの返り値がどのように変わるのか観察できます::" #: ../../faq/programming.rst:237 msgid "" "In order to avoid this, you need to save the values in variables local to " "the lambdas, so that they don't rely on the value of the global ``x``::" msgstr "" "これを避けるためには、グローバルの ``x`` の値に依存しないために、ラムダにとっ" "てのローカル変数に値を保存する必要があります::" #: ../../faq/programming.rst:244 msgid "" "Here, ``n=x`` creates a new variable ``n`` local to the lambda and computed " "when the lambda is defined so that it has the same value that ``x`` had at " "that point in the loop. This means that the value of ``n`` will be ``0`` in " "the first lambda, ``1`` in the second, ``2`` in the third, and so on. " "Therefore each lambda will now return the correct result::" msgstr "" "ここで、``n=x`` は新しいラムダにとってのローカル変数 ``n`` を作成し、ラムダが" "定義されるときに計算されるので、ループのその時点での ``x`` と同じ値を持ってい" "ます。これは、1 つ目のラムダでは ``n`` の値は ``0`` になり、2 つ目では " "``1``、3 つ目では ``2`` 以下同様、となることを意味します。従って、それぞれの" "ラムダは今や正しい値を返すようになりました::" #: ../../faq/programming.rst:255 msgid "" "Note that this behaviour is not peculiar to lambdas, but applies to regular " "functions too." msgstr "" "この動作はラムダに特有なものではなく、通常の関数にも適用されることに注意して" "ください。" #: ../../faq/programming.rst:260 msgid "How do I share global variables across modules?" msgstr "グローバル変数をモジュール間で共有するにはどうしたらいいですか?" #: ../../faq/programming.rst:262 msgid "" "The canonical way to share information across modules within a single " "program is to create a special module (often called config or cfg). Just " "import the config module in all modules of your application; the module then " "becomes available as a global name. Because there is only one instance of " "each module, any changes made to the module object get reflected " "everywhere. For example:" msgstr "" "一つのプログラムのモジュール間で情報を共有する正準な方法は、特別なモジュール " "(しばしば config や cfg と呼ばれる) を作ることです。単に設定モジュールをアプ" "リケーションのすべてのモジュールにインポートしてください。このモジュールはグ" "ローバルな名前として使えます。それぞれのモジュールのただ一つのインスタンスが" "あるので、設定モジュールオブジェクトに対するいかなる変更も全体に反映されま" "す。例えば:" #: ../../faq/programming.rst:268 msgid "config.py::" msgstr "config.py::" #: ../../faq/programming.rst:272 msgid "mod.py::" msgstr "mod.py::" #: ../../faq/programming.rst:277 msgid "main.py::" msgstr "main.py::" #: ../../faq/programming.rst:283 msgid "" "Note that using a module is also the basis for implementing the singleton " "design pattern, for the same reason." msgstr "" "なお、同じ理由から、モジュールを使うということは、シングルトンデザインパター" "ンを実装することの基礎でもあります。" #: ../../faq/programming.rst:288 msgid "What are the \"best practices\" for using import in a module?" msgstr "モジュールで import を使う際の「ベストプラクティス」は何ですか?" #: ../../faq/programming.rst:290 msgid "" "In general, don't use ``from modulename import *``. Doing so clutters the " "importer's namespace, and makes it much harder for linters to detect " "undefined names." msgstr "" "一般的に ``from modulename import *`` を使ってはいけません。そのようにすると" "インポータの名前空間は汚染され、linter が未定義の名前を発見することが難しくな" "ります。" #: ../../faq/programming.rst:294 msgid "" "Import modules at the top of a file. Doing so makes it clear what other " "modules your code requires and avoids questions of whether the module name " "is in scope. Using one import per line makes it easy to add and delete " "module imports, but using multiple imports per line uses less screen space." msgstr "" "モジュールはファイルの先頭でインポートしてください。これによってコードが必要" "とする他のモジュールが明確になり、モジュール名がスコープに含まれるかどうかに" "迷わなくなります。行に一つのインポートにすると、モジュールのインポートの追加" "と削除が容易になりますが、行に複数のインポートにすると画面の領域が少なく済み" "ます。" #: ../../faq/programming.rst:299 msgid "It's good practice if you import modules in the following order:" msgstr "次の手順でモジュールをインポートするのが、良い習慣になります:" #: ../../faq/programming.rst:301 msgid "" "standard library modules -- e.g. :mod:`sys`, :mod:`os`, :mod:`argparse`, :" "mod:`re`" msgstr "" "標準ライブラリモジュール -- 例 :mod:`sys`、:mod:`os`、:mod:`argparse`、:mod:" "`re`" #: ../../faq/programming.rst:302 msgid "" "third-party library modules (anything installed in Python's site-packages " "directory) -- e.g. :mod:`!dateutil`, :mod:`!requests`, :mod:`!PIL.Image`" msgstr "" "サードパーティのライブラリモジュール (Python の site-packages ディレクトリに" "あるもの) -- 例 :mod:`!dateutil`、:mod:`!requests`、:mod:`!PIL.Image`、など" #: ../../faq/programming.rst:304 msgid "locally developed modules" msgstr "自前で開発したモジュール" #: ../../faq/programming.rst:306 msgid "" "It is sometimes necessary to move imports to a function or class to avoid " "problems with circular imports. Gordon McMillan says:" msgstr "" "循環参照の問題を避けるために、インポートを関数やクラスに移すことが必要なとき" "もあります。Gordon McMillan によれば:" #: ../../faq/programming.rst:309 msgid "" "Circular imports are fine where both modules use the \"import \" " "form of import. They fail when the 2nd module wants to grab a name out of " "the first (\"from module import name\") and the import is at the top level. " "That's because names in the 1st are not yet available, because the first " "module is busy importing the 2nd." msgstr "" "循環参照は両方のモジュールが \"import \" 形式のインポートを使っていれ" "ば大丈夫です。二つ目のモジュールが最初のモジュールから名前を確保しようとして " "(\"from module import name\")、そのインポートがトップレベルにあると駄目です。" "最初のモジュールが二つ目のモジュールをインポートするのに忙しくて、最初のモ" "ジュールの名前が利用可能になっていないからです。" #: ../../faq/programming.rst:315 msgid "" "In this case, if the second module is only used in one function, then the " "import can easily be moved into that function. By the time the import is " "called, the first module will have finished initializing, and the second " "module can do its import." msgstr "" "この状況では、二つ目のモジュールが一つの関数の中でのみ使われているならば、そ" "のインポートは簡単に関数の中に移せます。インポートが呼ばれたとき、最初のモ" "ジュールは初期化を完了していて、二つ目のモジュールは自分のインポートをできま" "す。" #: ../../faq/programming.rst:320 msgid "" "It may also be necessary to move imports out of the top level of code if " "some of the modules are platform-specific. In that case, it may not even be " "possible to import all of the modules at the top of the file. In this case, " "importing the correct modules in the corresponding platform-specific code is " "a good option." msgstr "" "プラットフォーム依存のモジュールがあるときには、インポートをトップレベルの外" "に動かすことも必要です。この場合、ファイルの先頭ではすべてのモジュールをイン" "ポートすることさえできないかもしれません。この場合は、対応するプラットフォー" "ムに合わせたコードで正しいモジュールをインポートすることを選ぶと良いです。" #: ../../faq/programming.rst:325 msgid "" "Only move imports into a local scope, such as inside a function definition, " "if it's necessary to solve a problem such as avoiding a circular import or " "are trying to reduce the initialization time of a module. This technique is " "especially helpful if many of the imports are unnecessary depending on how " "the program executes. You may also want to move imports into a function if " "the modules are only ever used in that function. Note that loading a module " "the first time may be expensive because of the one time initialization of " "the module, but loading a module multiple times is virtually free, costing " "only a couple of dictionary lookups. Even if the module name has gone out " "of scope, the module is probably available in :data:`sys.modules`." msgstr "" "循環参照の問題を避けたりモジュールの初期化にかかる時間を減らしたりしたいな" "ら、単にインポートを関数定義の中などのローカルなスコープに移してください。こ" "の手法は多くのインポートがプログラムがどのように実行されるかに依存しなくてよ" "いときに特に有効です。ある関数の中でのみモジュールが使われるのなら、インポー" "トをその関数の中に移すことを考えてもいいでしょう。なお、モジュールを読み込む" "最初の回はモジュールの初期化の時間のために高価になりえますが、複数回目にモ" "ジュールを読み込むのは事実上無料、辞書探索の数回のコストだけで済みます。モ" "ジュール名がスコープから外れてさえ、そのモジュールはおそらく :data:`sys." "modules` から利用できるでしょう。" #: ../../faq/programming.rst:338 msgid "Why are default values shared between objects?" msgstr "なぜオブジェクト間でデフォルト値が共有されるのですか?" #: ../../faq/programming.rst:340 msgid "" "This type of bug commonly bites neophyte programmers. Consider this " "function::" msgstr "" "この種のバグがよく初心者プログラマに噛み付きます。この関数を考えてみてくださ" "い::" #: ../../faq/programming.rst:347 msgid "" "The first time you call this function, ``mydict`` contains a single item. " "The second time, ``mydict`` contains two items because when ``foo()`` begins " "executing, ``mydict`` starts out with an item already in it." msgstr "" "初めてこの関数を呼び出した時、``mydict`` には一つの要素があります。二回目に" "は、``foo()`` が実行されるときに ``mydict`` には初めから一つの要素をすでに" "持っているので、``mydict`` には二つの要素があります。" #: ../../faq/programming.rst:351 msgid "" "It is often expected that a function call creates new objects for default " "values. This is not what happens. Default values are created exactly once, " "when the function is defined. If that object is changed, like the " "dictionary in this example, subsequent calls to the function will refer to " "this changed object." msgstr "" "関数の呼び出しによって、デフォルトの値に対する新しいオブジェクトが作られるの" "だと予想しがちです。実はそうなりません。デフォルト値は、関数が定義されたとき" "に一度だけ生成されます。この例の辞書のように、そのオブジェクトが変更されたと" "き、その後の関数の呼び出しは変更後のオブジェクトを参照します。" #: ../../faq/programming.rst:356 msgid "" "By definition, immutable objects such as numbers, strings, tuples, and " "``None``, are safe from change. Changes to mutable objects such as " "dictionaries, lists, and class instances can lead to confusion." msgstr "" "定義の時に、数、文字列、タプル、``None`` など、イミュータブルなオブジェクトを" "使うと変更される危険がありません。辞書、リスト、クラスインスタンスなどの" "ミュータブルなオブジェクトは混乱のもとです。" #: ../../faq/programming.rst:360 msgid "" "Because of this feature, it is good programming practice to not use mutable " "objects as default values. Instead, use ``None`` as the default value and " "inside the function, check if the parameter is ``None`` and create a new " "list/dictionary/whatever if it is. For example, don't write::" msgstr "" "この性質から、ミュータブルなオブジェクトをデフォルト値として使わないプログラ" "ミング手法がいいです。代わりに、``None`` をデフォルト値に使い、そのパラメタ" "が ``None`` である時にだけ、関数の内部で新しいリスト/辞書/その他をつくるよう" "にしてください。例えば、こう書かずに::" #: ../../faq/programming.rst:368 msgid "but::" msgstr "代わりに::" #: ../../faq/programming.rst:374 msgid "" "This feature can be useful. When you have a function that's time-consuming " "to compute, a common technique is to cache the parameters and the resulting " "value of each call to the function, and return the cached value if the same " "value is requested again. This is called \"memoizing\", and can be " "implemented like this::" msgstr "" "この性質が便利なこともあります。時間のかかる計算を行う関数があるときに使われ" "る一般的な技法は、関数が呼び出されるごとにパラメタと結果の値をキャッシュし、" "再び同じ値が要求されたらキャッシュされた値を返すというものです。これは " "\"memoizing\" と呼ばれ、このように実装されます::" #: ../../faq/programming.rst:389 msgid "" "You could use a global variable containing a dictionary instead of the " "default value; it's a matter of taste." msgstr "" "デフォルト値の代わりに、辞書を含むグローバル変数も使えます。これは好みの問題" "です。" #: ../../faq/programming.rst:394 msgid "" "How can I pass optional or keyword parameters from one function to another?" msgstr "" "オプションパラメータやキーワードパラメータを関数から関数へ渡すにはどうしたら" "いいですか?" #: ../../faq/programming.rst:396 msgid "" "Collect the arguments using the ``*`` and ``**`` specifiers in the " "function's parameter list; this gives you the positional arguments as a " "tuple and the keyword arguments as a dictionary. You can then pass these " "arguments when calling another function by using ``*`` and ``**``::" msgstr "" "関数のパラメータリストに引数を ``*`` と ``**`` 指定子 (specifier) で集めてく" "ださい。そうすれば、位置引数をタプルとして、キーワード引数を辞書として得られ" "ます。これで、他の関数を呼び出すときに ``*`` と ``**`` を使ってそれらの引数を" "渡せます::" #: ../../faq/programming.rst:415 msgid "What is the difference between arguments and parameters?" msgstr "実引数と仮引数の違いは何ですか?" #: ../../faq/programming.rst:417 msgid "" ":term:`Parameters ` are defined by the names that appear in a " "function definition, whereas :term:`arguments ` are the values " "actually passed to a function when calling it. Parameters define what :term:" "`kind of arguments ` a function can accept. For example, given " "the function definition::" msgstr "" ":term:`仮引数 (parameter) ` は関数定義に表れる名前で定義されるのに" "対し、 :term:`実引数 (argument) ` は関数を呼び出すときに実際に渡す" "値のことです。仮引数は関数が受け取ることの出来る :term:`実引数の型 " "` を定義します。例えば、以下のような関数定義があったとして::" #: ../../faq/programming.rst:426 msgid "" "*foo*, *bar* and *kwargs* are parameters of ``func``. However, when calling " "``func``, for example::" msgstr "" "*foo*、*bar*、*kwargs* は ``func`` の仮引数です。一方、``func`` を呼び出すと" "きには、例えば::" #: ../../faq/programming.rst:431 msgid "the values ``42``, ``314``, and ``somevar`` are arguments." msgstr "``42``、``314``、``somevar`` という値は実引数です。" #: ../../faq/programming.rst:435 msgid "Why did changing list 'y' also change list 'x'?" msgstr "なぜ list 'y' を変更すると list 'x' も変更されるのですか?" #: ../../faq/programming.rst:437 msgid "If you wrote code like::" msgstr "次のようなコードを書いたとします::" #: ../../faq/programming.rst:447 msgid "" "you might be wondering why appending an element to ``y`` changed ``x`` too." msgstr "" "どうして ``y`` への要素の追加が ``x`` も変更してしまうのか疑問に思うかもしれ" "ません。 " #: ../../faq/programming.rst:449 msgid "There are two factors that produce this result:" msgstr "このような結果になる2つの要因があります:" #: ../../faq/programming.rst:451 msgid "" "Variables are simply names that refer to objects. Doing ``y = x`` doesn't " "create a copy of the list -- it creates a new variable ``y`` that refers to " "the same object ``x`` refers to. This means that there is only one object " "(the list), and both ``x`` and ``y`` refer to it." msgstr "" "変数とは、単にオブジェクトを参照するための名前に過ぎません。 ``y = x`` とする" "ことは、リストのコピーを作りません -- それは ``x`` が参照するのと同じオブジェ" "クトを参照する新しい変数 ``y`` を作ります。つまり、あるのは一つのオブジェクト" "(この場合リスト)だけであって、 ``x`` と ``y`` の両方がそれを参照しているので" "す。" #: ../../faq/programming.rst:455 msgid "" "Lists are :term:`mutable`, which means that you can change their content." msgstr "リストは :term:`mutable` です。内容を変更出来る、ということです。" #: ../../faq/programming.rst:457 msgid "" "After the call to :meth:`~list.append`, the content of the mutable object " "has changed from ``[]`` to ``[10]``. Since both the variables refer to the " "same object, using either name accesses the modified value ``[10]``." msgstr "" ":meth:`~list.append` 呼び出しの後、ミュータブルオブジェクトの内容が ``[]`` か" "ら ``[10]`` に変わります。 変数が同じオブジェクトを参照しているので、どちらの" "名前であっても変更された値 ``[10]`` にアクセスします。" #: ../../faq/programming.rst:461 msgid "If we instead assign an immutable object to ``x``::" msgstr "代わりに ``x`` にイミュータブルを代入すると::" #: ../../faq/programming.rst:471 msgid "" "we can see that in this case ``x`` and ``y`` are not equal anymore. This is " "because integers are :term:`immutable`, and when we do ``x = x + 1`` we are " "not mutating the int ``5`` by incrementing its value; instead, we are " "creating a new object (the int ``6``) and assigning it to ``x`` (that is, " "changing which object ``x`` refers to). After this assignment we have two " "objects (the ints ``6`` and ``5``) and two variables that refer to them " "(``x`` now refers to ``6`` but ``y`` still refers to ``5``)." msgstr "" "この場合ご覧の通り ``x`` と ``y`` はまったく同じではありませんね。これは整数" "が :term:`immutable` だからで、 ``x = x + 1`` は整数の ``5`` の値を変更してい" "るのではありません; 代わりに新しいオブジェクト(整数 ``6``)を作って ``x`` に代" "入しています (つまり ``x`` が参照するオブジェクトが変わります)。この代入の後" "では私たちは 2 つのオブジェクト(整数の ``6`` と ``5``)を持っていて、2 つの変" "数はそれらを参照しています(``x`` はいまや ``6`` を参照していますが ``y`` は " "``5`` を参照したままです)。" #: ../../faq/programming.rst:479 msgid "" "Some operations (for example ``y.append(10)`` and ``y.sort()``) mutate the " "object, whereas superficially similar operations (for example ``y = y + " "[10]`` and :func:`sorted(y) `) create a new object. In general in " "Python (and in all cases in the standard library) a method that mutates an " "object will return ``None`` to help avoid getting the two types of " "operations confused. So if you mistakenly write ``y.sort()`` thinking it " "will give you a sorted copy of ``y``, you'll instead end up with ``None``, " "which will likely cause your program to generate an easily diagnosed error." msgstr "" "ある演算 (たとえば ``y.append(10)``, ``y.sort()``) がオブジェクトを変更する一" "方で、外見上は似た演算 (たとえば ``y = y + [10]``, :func:`sorted(y) " "`) は新しいオブジェクトを作ります。Python では一般に (そして標準ライ" "ブラリの全てのケースで)、このような 2 つのタイプの演算にまつわる混乱を避ける" "ために、オブジェクトを変更するメソッドは ``None`` を返します。ですからもしあ" "なたが誤って ``y`` の複製の並び替えをするつもりで ``y.sort()`` と書いた場合に" "結果手にするのは ``None`` でしょうから、あなたのプログラムは簡単に診断出来る" "エラーを起こすでしょう。" #: ../../faq/programming.rst:488 msgid "" "However, there is one class of operations where the same operation sometimes " "has different behaviors with different types: the augmented assignment " "operators. For example, ``+=`` mutates lists but not tuples or ints " "(``a_list += [1, 2, 3]`` is equivalent to ``a_list.extend([1, 2, 3])`` and " "mutates ``a_list``, whereas ``some_tuple += (1, 2, 3)`` and ``some_int += " "1`` create new objects)." msgstr "" "しかしながら、同じ操作が型ごとに異なる振る舞いをする演算の種類が一つありま" "す: 累算代入演算です。例えば ``+=`` はリストを変更しますが、タプルや整数は変" "更しません(``a_list += [1, 2, 3]`` は ``a_list.extend([1, 2, 3])`` と同じ意味" "で、そして ``a_list`` を変更しますが、 ``some_tuple += (1, 2, 3)`` と " "``some_int += 1`` は新しいオブジェクトを作ります)。" #: ../../faq/programming.rst:495 msgid "In other words:" msgstr "言い換えると:" #: ../../faq/programming.rst:497 msgid "" "If we have a mutable object (:class:`list`, :class:`dict`, :class:`set`, " "etc.), we can use some specific operations to mutate it and all the " "variables that refer to it will see the change." msgstr "" "ミュータブルなオブジェクト(:class:`list`, :class:`dict`, :class:`set`, 等)を" "持っている場合、私たちはその内容を変更するある種の演算を使うことが出来、それ" "を参照している全ての変数はその変化を見ることになるでしょう。" #: ../../faq/programming.rst:500 msgid "" "If we have an immutable object (:class:`str`, :class:`int`, :class:`tuple`, " "etc.), all the variables that refer to it will always see the same value, " "but operations that transform that value into a new value always return a " "new object." msgstr "" "イミュータブルなオブジェクト(:class:`str`, :class:`int`, :class:`tuple`, 等)" "を持っている場合、それを参照している全ての変数は同じ値を参照しているでしょう" "が、持っている値を新しい値に変換する演算はいつでも新しいオブジェクトを返しま" "す。" #: ../../faq/programming.rst:505 msgid "" "If you want to know if two variables refer to the same object or not, you " "can use the :keyword:`is` operator, or the built-in function :func:`id`." msgstr "" "2つの変数が同じオブジェクトを参照しているかどうかが知りたければ、 :keyword:" "`is` 演算子や組み込み関数 :func:`id` が使えます。" #: ../../faq/programming.rst:510 msgid "How do I write a function with output parameters (call by reference)?" msgstr "出力引数のある関数 (参照渡し) はどのように書きますか?" #: ../../faq/programming.rst:512 msgid "" "Remember that arguments are passed by assignment in Python. Since " "assignment just creates references to objects, there's no alias between an " "argument name in the caller and callee, and so no call-by-reference per se. " "You can achieve the desired effect in a number of ways." msgstr "" "前提として、Python では引数は代入によって渡されます。代入はオブジェクトへの参" "照を作るだけなので、呼び出し元と呼び出し先にある引数名の間にエイリアスはあり" "ませんし、参照渡しそれ自体はありません。望む効果を得るためには幾つかの方法が" "あります。" #: ../../faq/programming.rst:517 msgid "By returning a tuple of the results::" msgstr "結果のタプルを返すことによって::" #: ../../faq/programming.rst:528 msgid "This is almost always the clearest solution." msgstr "これはたいてい一番明確な方法です。" #: ../../faq/programming.rst:530 msgid "" "By using global variables. This isn't thread-safe, and is not recommended." msgstr "" "グローバル変数を使って。これはスレッドセーフでないので、推奨されません。" #: ../../faq/programming.rst:532 msgid "By passing a mutable (changeable in-place) object::" msgstr "" "ミュータブルな (インプレースに変更可能な) オブジェクトを渡すことによって::" #: ../../faq/programming.rst:543 msgid "By passing in a dictionary that gets mutated::" msgstr "変更される辞書に渡すことによって::" #: ../../faq/programming.rst:554 msgid "Or bundle up values in a class instance::" msgstr "または、クラスインスタンスに値を同梱することによって::" #: ../../faq/programming.rst:571 msgid "There's almost never a good reason to get this complicated." msgstr "このような複雑なことをする理由はめったに無いでしょう。" #: ../../faq/programming.rst:573 msgid "Your best choice is to return a tuple containing the multiple results." msgstr "一番の選択は、複数の結果を含むタプルを返すことです。" #: ../../faq/programming.rst:577 msgid "How do you make a higher order function in Python?" msgstr "Python で高次関数はどのようにつくりますか?" #: ../../faq/programming.rst:579 msgid "" "You have two choices: you can use nested scopes or you can use callable " "objects. For example, suppose you wanted to define ``linear(a,b)`` which " "returns a function ``f(x)`` that computes the value ``a*x+b``. Using nested " "scopes::" msgstr "" "二つの方法があります: ネストされたスコープを使う方法と、呼び出し可能オブジェ" "クトを使う方法です。例えば、``a*x+b`` の値を計算する ``f(x)`` 関数を返す " "``linear(a,b)`` を定義したいとします。ネストされたスコープを使うと::" #: ../../faq/programming.rst:588 msgid "Or using a callable object::" msgstr "また、呼び出し可能オブジェクトを使うと::" #: ../../faq/programming.rst:598 msgid "In both cases, ::" msgstr "どちらの場合でも、 ::" #: ../../faq/programming.rst:602 msgid "gives a callable object where ``taxes(10e6) == 0.3 * 10e6 + 2``." msgstr "" "とすれば、``taxes(10e6) == 0.3 * 10e6 + 2`` となるような呼び出し可能オブジェ" "クトを得られます。" #: ../../faq/programming.rst:604 msgid "" "The callable object approach has the disadvantage that it is a bit slower " "and results in slightly longer code. However, note that a collection of " "callables can share their signature via inheritance::" msgstr "" "呼び出し可能オブジェクトを使う方法は、少し遅くなり、わずかにコードが長くなる" "という短所があります。ですが、継承を使って呼び出し可能オブジェクト同士で記号" "を共有することもできます::" #: ../../faq/programming.rst:613 msgid "Object can encapsulate state for several methods::" msgstr "オブジェクトはいくつかのメソッドに状態をカプセル化できます::" #: ../../faq/programming.rst:631 msgid "" "Here ``inc()``, ``dec()`` and ``reset()`` act like functions which share the " "same counting variable." msgstr "" "ここで、``inc()``、``dec()``、``reset()`` は同じカウント変数を共有する関数の" "ようにふるまいます。" #: ../../faq/programming.rst:636 msgid "How do I copy an object in Python?" msgstr "Python のオブジェクトはどのようにコピーしますか?" #: ../../faq/programming.rst:638 msgid "" "In general, try :func:`copy.copy` or :func:`copy.deepcopy` for the general " "case. Not all objects can be copied, but most can." msgstr "" "一般的に、普通は :func:`copy.copy` や :func:`copy.deepcopy` を試してくださ" "い。何でもコピーできるとは限りませんが、たいていはできます。" #: ../../faq/programming.rst:641 msgid "" "Some objects can be copied more easily. Dictionaries have a :meth:`~dict." "copy` method::" msgstr "" "もっと簡単にコピーできるオブジェクトもあります。辞書には :meth:`~dict.copy` " "メソッドがあります::" #: ../../faq/programming.rst:646 msgid "Sequences can be copied by slicing::" msgstr "シーケンスはスライシングでコピーできます::" #: ../../faq/programming.rst:652 msgid "How can I find the methods or attributes of an object?" msgstr "オブジェクトのメソッドや属性はどのように見つけますか?" #: ../../faq/programming.rst:654 msgid "" "For an instance ``x`` of a user-defined class, :func:`dir(x) ` returns " "an alphabetized list of the names containing the instance attributes and " "methods and attributes defined by its class." msgstr "" "ユーザー定義クラスのインスタンス ``x`` で、:func:`dir(x) `,< はインスタ" "ンス属性とそのクラスで定義されたメソッドや属性を含む名前のアルファベット順リ" "ストを返します。" #: ../../faq/programming.rst:660 msgid "How can my code discover the name of an object?" msgstr "コードはどのようにオブジェクトの名前を見つけるのですか?" #: ../../faq/programming.rst:662 msgid "" "Generally speaking, it can't, because objects don't really have names. " "Essentially, assignment always binds a name to a value; the same is true of " "``def`` and ``class`` statements, but in that case the value is a callable. " "Consider the following code::" msgstr "" "概して、オブジェクトは本当は名前を持たないので、見つけることはできません。本" "質的には、代入とはいつも値に名前を束縛することです。``def`` と ``class`` 文も" "同じですが、この場合は値はコーラブルです。以下のコードを考えてみましょう::" #: ../../faq/programming.rst:678 msgid "" "Arguably the class has a name: even though it is bound to two names and " "invoked through the name ``B`` the created instance is still reported as an " "instance of class ``A``. However, it is impossible to say whether the " "instance's name is ``a`` or ``b``, since both names are bound to the same " "value." msgstr "" "おそらく、このクラスには名前があります。このクラスは二つの名前に縛られて、名" "前 ``B`` を通して呼び出されますが、それでもクラス ``A`` のインスタンスとして" "報告されるのです。しかし、両方の名前が同じ値に束縛されている以上、このインス" "タンスの名前が ``a`` か ``b`` か決めることはできないのです。" #: ../../faq/programming.rst:683 msgid "" "Generally speaking it should not be necessary for your code to \"know the " "names\" of particular values. Unless you are deliberately writing " "introspective programs, this is usually an indication that a change of " "approach might be beneficial." msgstr "" "概して、コードにとってある値の「名前を知っている」事は重要ではありません。あ" "なたがわざと内省的なコードを書いているのでない限り、方針を変えた方がいいかも" "しれないということになるでしょう。" #: ../../faq/programming.rst:688 msgid "" "In comp.lang.python, Fredrik Lundh once gave an excellent analogy in answer " "to this question:" msgstr "" "comp.lang.python で、Fredrik Lundh はこの問題の答えとして素晴らしい喩えをして" "くれました:" #: ../../faq/programming.rst:691 msgid "" "The same way as you get the name of that cat you found on your porch: the " "cat (object) itself cannot tell you its name, and it doesn't really care -- " "so the only way to find out what it's called is to ask all your neighbours " "(namespaces) if it's their cat (object)..." msgstr "" "玄関にいた猫の名前を知るのと同じ方法です: その猫 (オブジェクト) 自体はその名" "前を言うことができないし、それは実は問題ではありません -- その猫が何と呼ばれ" "ているかを知る唯一の方法は、すべての隣人 (名前空間) にその猫 (オブジェクト) " "が何と呼ばれているかを聞くことです。" #: ../../faq/programming.rst:696 msgid "" "....and don't be surprised if you'll find that it's known by many names, or " "no name at all!" msgstr "" "……そして、その猫が沢山の名前で知られていたり、逆に全く名前が無かったりしても" "驚かないでください!" #: ../../faq/programming.rst:701 msgid "What's up with the comma operator's precedence?" msgstr "カンマ演算子はなぜ優先されるのですか?" #: ../../faq/programming.rst:703 msgid "Comma is not an operator in Python. Consider this session::" msgstr "" "カンマは Python では演算子ではありません。このセッションを考えてください::" #: ../../faq/programming.rst:708 msgid "" "Since the comma is not an operator, but a separator between expressions the " "above is evaluated as if you had entered::" msgstr "" "カンマは演算子ではなく、式の分離子なので、上の式は次の式と同じように評価され" "ます::" #: ../../faq/programming.rst:713 msgid "not::" msgstr "こうではありません::" #: ../../faq/programming.rst:717 msgid "" "The same is true of the various assignment operators (``=``, ``+=`` etc). " "They are not truly operators but syntactic delimiters in assignment " "statements." msgstr "" "他のさまざまな演算子(``=``、``+=`` など)も同じです。これらは真の演算子ではあ" "りませんが、代入文の構文上のデリミタです。" #: ../../faq/programming.rst:722 msgid "Is there an equivalent of C's \"?:\" ternary operator?" msgstr "C の \"?:\" 三項演算子と等価なものはありますか?" #: ../../faq/programming.rst:724 msgid "Yes, there is. The syntax is as follows::" msgstr "はい、あります。構文は以下のようになります::" #: ../../faq/programming.rst:731 msgid "" "Before this syntax was introduced in Python 2.5, a common idiom was to use " "logical operators::" msgstr "" "この構文が導入された 2.5 以前のバージョンに関しては、論理演算子を使ったこのイ" "ディオムが一般的でした::" #: ../../faq/programming.rst:736 msgid "" "However, this idiom is unsafe, as it can give wrong results when *on_true* " "has a false boolean value. Therefore, it is always better to use the ``... " "if ... else ...`` form." msgstr "" "しかし、このイディオムは安全ではありません。*on_true* のブール値が偽であると" "きに間違った結果を与えることがあります。ですから、いつでも ``... if ... " "else ...`` 形式を使ったほうが良いです。" #: ../../faq/programming.rst:742 msgid "Is it possible to write obfuscated one-liners in Python?" msgstr "Python で解し難いワンライナーを書くことはできますか?" #: ../../faq/programming.rst:744 msgid "" "Yes. Usually this is done by nesting :keyword:`lambda` within :keyword:`!" "lambda`. See the following three examples, slightly adapted from Ulf " "Bartelt::" msgstr "" "はい。そういうものはたいてい、 :keyword:`!lambda` の中に :keyword:`lambda` が" "ネストされています。Ulf Bartelt によるものを少しアレンジした下の3つの例を見" "てください::" #: ../../faq/programming.rst:771 msgid "Don't try this at home, kids!" msgstr "よい子はまねしないでね!" #: ../../faq/programming.rst:777 msgid "What does the slash(/) in the parameter list of a function mean?" msgstr "関数の引数リストにあるスラッシュ (/) は何を意味しますか?" #: ../../faq/programming.rst:779 msgid "" "A slash in the argument list of a function denotes that the parameters prior " "to it are positional-only. Positional-only parameters are the ones without " "an externally usable name. Upon calling a function that accepts positional-" "only parameters, arguments are mapped to parameters based solely on their " "position. For example, :func:`divmod` is a function that accepts positional-" "only parameters. Its documentation looks like this::" msgstr "" "パラメータ関数の仮引数にあるスラッシュは、それより前にある仮引数は位置専用引" "数であることを示します。\n" "位置専用引数は、外で使える名前を持たない仮引数です。\n" "位置専用引数を受け付ける関数の呼び出しにおいて、実引数はその位置だけに基づい" "て仮引数に対応付けられます。\n" "例えば、 :func:`divmod` は位置専用引数を受け付けます。\n" "そのドキュメントは次のようになります::" #: ../../faq/programming.rst:792 msgid "" "The slash at the end of the parameter list means that both parameters are " "positional-only. Thus, calling :func:`divmod` with keyword arguments would " "lead to an error::" msgstr "" "この引数リストの末尾にスラッシュは、この2つの仮引数が両方とも位置専用引数であ" "ることを意味します。\n" "したがって、:func:`divmod` をキーワード引数を使って呼び出すとエラーになりま" "す::" #: ../../faq/programming.rst:803 msgid "Numbers and strings" msgstr "数と文字列" #: ../../faq/programming.rst:806 msgid "How do I specify hexadecimal and octal integers?" msgstr "十六進数や八進数を指定するにはどうしたらいいですか?" #: ../../faq/programming.rst:808 msgid "" "To specify an octal digit, precede the octal value with a zero, and then a " "lower or uppercase \"o\". For example, to set the variable \"a\" to the " "octal value \"10\" (8 in decimal), type::" msgstr "" "八進数を指定するには、八進数での値の先頭に 0 と \"o\" (小文字または大文字) を" "加えてください。たとえば、変数 \"a\" に八進数での \"10\" (十進数での\"8\") を" "代入するには、こう打ってください::" #: ../../faq/programming.rst:816 msgid "" "Hexadecimal is just as easy. Simply precede the hexadecimal number with a " "zero, and then a lower or uppercase \"x\". Hexadecimal digits can be " "specified in lower or uppercase. For example, in the Python interpreter::" msgstr "" "十六進数も簡単です。ただ十六進数での値の先頭に 0 と \"x\" (小文字または大文" "字) を加えてください。十六進数は小文字でも大文字でも指定できます。たとえば、" "Python インタプリタで::" #: ../../faq/programming.rst:829 msgid "Why does -22 // 10 return -3?" msgstr "なぜ -22 // 10 は -3 を返すのですか?" #: ../../faq/programming.rst:831 msgid "" "It's primarily driven by the desire that ``i % j`` have the same sign as " "``j``. If you want that, and also want::" msgstr "" "``i % j`` が ``j`` と同じ符号であってほしいことに基づいています。それに加えて" "以下のようにもしたいとすると::" #: ../../faq/programming.rst:836 msgid "" "then integer division has to return the floor. C also requires that " "identity to hold, and then compilers that truncate ``i // j`` need to make " "``i % j`` have the same sign as ``i``." msgstr "" "整数除算は床を返すことになります。C にも C の一貫性があって、``i % j`` が " "``i`` と同じ符号を持つように ``i // j`` を丸めています。" #: ../../faq/programming.rst:840 msgid "" "There are few real use cases for ``i % j`` when ``j`` is negative. When " "``j`` is positive, there are many, and in virtually all of them it's more " "useful for ``i % j`` to be ``>= 0``. If the clock says 10 now, what did it " "say 200 hours ago? ``-190 % 12 == 2`` is useful; ``-190 % 12 == -10`` is a " "bug waiting to bite." msgstr "" "``i % j`` は、``j`` が負の時には実際にはほとんど使いません。``j`` が正なら、" "たくさん使います。その事実上すべての場合、``i % j`` は ``>= 0`` となる方が便" "利です。時計が 10 時を指している時、その 200 時間前は何時でしょうか。``-190 " "% 12 == 2`` となるのが便利です。``-190 % 12 == -10`` は噛み付きかねないバグで" "す。" #: ../../faq/programming.rst:848 msgid "How do I get int literal attribute instead of SyntaxError?" msgstr "どうすれば SyntaxError を起こさずに整数リテラルの属性を得られますか?" #: ../../faq/programming.rst:850 msgid "" "Trying to lookup an ``int`` literal attribute in the normal manner gives a :" "exc:`SyntaxError` because the period is seen as a decimal point::" msgstr "" "ふつうの方法で ``int`` リテラルの属性を探そうとすると、ピリオドが小数点とみな" "され、:exc:`SyntaxError` となります::" #: ../../faq/programming.rst:859 msgid "" "The solution is to separate the literal from the period with either a space " "or parentheses." msgstr "解決策は、リテラルとピリオドを スペースや括弧で分けることです。" #: ../../faq/programming.rst:869 msgid "How do I convert a string to a number?" msgstr "文字列を数に変換するにはどうしたらいいですか?" #: ../../faq/programming.rst:871 msgid "" "For integers, use the built-in :func:`int` type constructor, e.g. " "``int('144') == 144``. Similarly, :func:`float` converts to floating-point, " "e.g. ``float('144') == 144.0``." msgstr "" "整数に変換するには、組み込みの :func:`int` 型コンストラクタを使ってください。" "例えば、 ``int('144') == 144`` です。同様に、 :func:`float` は浮動小数点に変" "換します。例えば、 ``float('144') == 144.0`` です。" #: ../../faq/programming.rst:875 msgid "" "By default, these interpret the number as decimal, so that ``int('0144') == " "144`` holds true, and ``int('0x144')`` raises :exc:`ValueError`. " "``int(string, base)`` takes the base to convert from as a second optional " "argument, so ``int( '0x144', 16) == 324``. If the base is specified as 0, " "the number is interpreted using Python's rules: a leading '0o' indicates " "octal, and '0x' indicates a hex number." msgstr "" "デフォルトでは、これらは数を十進数として解釈するので、 ``int('0144') == " "144`` は成立しますが ``int('0x144')`` は :exc:`ValueError` を送出します。 " "``int(string, base)`` はオプションの第二引数をとって変換元の基数にします。つ" "まり ``int( '0x144', 16) == 324`` です。基数が 0 と指定された場合、その数は " "Python の基準によって解釈されます。先頭が '0o' なら八進数で、'0x' なら十六進" "数を表します。" #: ../../faq/programming.rst:882 msgid "" "Do not use the built-in function :func:`eval` if all you need is to convert " "strings to numbers. :func:`eval` will be significantly slower and it " "presents a security risk: someone could pass you a Python expression that " "might have unwanted side effects. For example, someone could pass " "``__import__('os').system(\"rm -rf $HOME\")`` which would erase your home " "directory." msgstr "" "文字列を数に変換するだけのために :func:`eval` を使わないでください。 :func:" "`eval` は特に遅いですし、セキュリティ上のリスクもあります。求められない副作用" "を持つような Python の式を渡そうとする人がいるかも知れません。例えば、あなた" "のホームディレクトリを消去する ``__import__('os').system(\"rm -rf $HOME\")`` " "を渡そうとする人がいるかも知れません。" #: ../../faq/programming.rst:889 msgid "" ":func:`eval` also has the effect of interpreting numbers as Python " "expressions, so that e.g. ``eval('09')`` gives a syntax error because Python " "does not allow leading '0' in a decimal number (except '0')." msgstr "" ":func:`eval` にも数を Python の式として解釈する機能があります。だから例え" "ば、 ``eval('09')`` は構文エラー起こします。Python は ('0' 以外の) 十進数を " "'0' で始めてはならないからです。" #: ../../faq/programming.rst:895 msgid "How do I convert a number to a string?" msgstr "数を文字列に変換するにはどうしたらいいですか?" #: ../../faq/programming.rst:897 msgid "" "To convert, e.g., the number ``144`` to the string ``'144'``, use the built-" "in type constructor :func:`str`. If you want a hexadecimal or octal " "representation, use the built-in functions :func:`hex` or :func:`oct`. For " "fancy formatting, see the :ref:`f-strings` and :ref:`formatstrings` " "sections, e.g. ``\"{:04d}\".format(144)`` yields ``'0144'`` and ``\"{:.3f}\"." "format(1.0/3.0)`` yields ``'0.333'``." msgstr "" "例えば、``144`` という数を ``'144'`` という文字列に変換したいなら、組み込み型" "のコンストラクタ :func:`str` を使ってください。\n" "十六進数や八進数にしたければ、組み込み関数の :func:`hex` や :func:`oct` を" "使ってください。\n" "手の込んだフォーマット形式を使うなら、 :ref:`f-strings` と :ref:" "`formatstrings` の節を参照してください。\n" "例えば、 ``\"{:04d}\".format(144)`` は ``'0144'`` になり、 ``\"{:.3f}\"." "format(1.0/3.0)`` は ``'0.333'`` になります。" #: ../../faq/programming.rst:906 msgid "How do I modify a string in place?" msgstr "文字列をインプレースに変更するにはどうしたらいいですか?" #: ../../faq/programming.rst:908 msgid "" "You can't, because strings are immutable. In most situations, you should " "simply construct a new string from the various parts you want to assemble it " "from. However, if you need an object with the ability to modify in-place " "unicode data, try using an :class:`io.StringIO` object or the :mod:`array` " "module::" msgstr "" "文字列はイミュータブルなので、それはできません。殆どの場合、組み立てたい個別" "の部品から単純に新しい文字列を構成するべきです。しかし、Unicode データをイン" "プレースに変更できるオブジェクトが必要なら、 :mod:`array` モジュールの :" "class:`io.StringIO` オブジェクトを試してください::" #: ../../faq/programming.rst:938 msgid "How do I use strings to call functions/methods?" msgstr "関数やメソッドを呼ぶのに文字列を使うにはどうしたらいいですか?" #: ../../faq/programming.rst:940 msgid "There are various techniques." msgstr "様々なテクニックがあります。" #: ../../faq/programming.rst:942 msgid "" "The best is to use a dictionary that maps strings to functions. The primary " "advantage of this technique is that the strings do not need to match the " "names of the functions. This is also the primary technique used to emulate " "a case construct::" msgstr "" "一番いいのは、文字列を関数に対応させる辞書を使うことです。このテクニックの一" "番の利点は、文字列が関数の名前と同じ必要がないことです。この方法は case 構造" "をエミュレートするための一番のテクニックでもあります::" #: ../../faq/programming.rst:957 msgid "Use the built-in function :func:`getattr`::" msgstr "組み込み関数の :func:`getattr` を使う方法::" #: ../../faq/programming.rst:962 msgid "" "Note that :func:`getattr` works on any object, including classes, class " "instances, modules, and so on." msgstr "" "なお、 :func:`getattr` はクラス、クラスインスタンス、モジュールなど、どんなオ" "ブジェクトにも使えます。" #: ../../faq/programming.rst:965 msgid "This is used in several places in the standard library, like this::" msgstr "これは標準ライブラリでも何箇所か使われています。このように::" #: ../../faq/programming.rst:978 msgid "Use :func:`locals` to resolve the function name::" msgstr ":func:`locals` を使って関数名を決める方法::" #: ../../faq/programming.rst:990 msgid "" "Is there an equivalent to Perl's chomp() for removing trailing newlines from " "strings?" msgstr "" "文字列から後端の改行を取り除く Perl の chomp() に相当するものはありますか?" #: ../../faq/programming.rst:992 msgid "" "You can use ``S.rstrip(\"\\r\\n\")`` to remove all occurrences of any line " "terminator from the end of the string ``S`` without removing other trailing " "whitespace. If the string ``S`` represents more than one line, with several " "empty lines at the end, the line terminators for all the blank lines will be " "removed::" msgstr "" "``S.rstrip(\"\\r\\n\")`` を使って文字列 ``S`` の終端から他の空白文字を取り除" "くことなくすべての行末記号を取り除くことができます。文字列 ``S`` が複数行を表" "し、終端に空行があるとき、そのすべての空行も取り除かれます::" #: ../../faq/programming.rst:1004 msgid "" "Since this is typically only desired when reading text one line at a time, " "using ``S.rstrip()`` this way works well." msgstr "" "これは典型的に一度に一行ずつテキストを読みたい時にのみ使われるので、``S." "rstrip()`` をこの方法で使うとうまくいきます。" #: ../../faq/programming.rst:1009 msgid "Is there a scanf() or sscanf() equivalent?" msgstr "scanf() や sscanf() と同等なものはありますか?" #: ../../faq/programming.rst:1011 msgid "Not as such." msgstr "そのようなものはありません。" #: ../../faq/programming.rst:1013 msgid "" "For simple input parsing, the easiest approach is usually to split the line " "into whitespace-delimited words using the :meth:`~str.split` method of " "string objects and then convert decimal strings to numeric values using :" "func:`int` or :func:`float`. :meth:`!split()` supports an optional \"sep\" " "parameter which is useful if the line uses something other than whitespace " "as a separator." msgstr "" "簡単な入力解析で、多くの場合に一番簡単な方法は、文字列オブジェクトの :meth:" "`~str.split` メソッドで行を空白文字で区切られた単語に分け、十進数の文字列を :" "func:`int` や :func:`float` で数値に変換することです。 :meth:`!split()` には" "オプションの \"sep\" 変数があり、行に空白文字以外の区切りを使っているときに便" "利です。" #: ../../faq/programming.rst:1019 msgid "" "For more complicated input parsing, regular expressions are more powerful " "than C's ``sscanf`` and better suited for the task." msgstr "" "もっと複雑な入力解析をしたいなら、C の ``sscanf`` よりも正規表現の方が便利で" "すし、この処理に向いています。" #: ../../faq/programming.rst:1024 msgid "What does 'UnicodeDecodeError' or 'UnicodeEncodeError' error mean?" msgstr "'UnicodeDecodeError' や 'UnicodeEncodeError' はどういう意味ですか?" #: ../../faq/programming.rst:1026 msgid "See the :ref:`unicode-howto`." msgstr ":ref:`unicode-howto` を参照して下さい。" #: ../../faq/programming.rst:1032 msgid "Can I end a raw string with an odd number of backslashes?" msgstr "raw string を奇数個のバックスラッシュで終えることはできますか?" #: ../../faq/programming.rst:1034 msgid "" "A raw string ending with an odd number of backslashes will escape the " "string's quote::" msgstr "" "奇数個のバックスラッシュで終わる raw string は文字列のクォートをエスケープし" "ます::" #: ../../faq/programming.rst:1042 msgid "" "There are several workarounds for this. One is to use regular strings and " "double the backslashes::" msgstr "" "これにはいくつかの回避策があります。ひとつは通常文字列と二重バックスラッシュ" "を使うことです::" #: ../../faq/programming.rst:1048 msgid "" "Another is to concatenate a regular string containing an escaped backslash " "to the raw string::" msgstr "" "もうひとつは、エスケープされたバックスラッシュを含む通常の文字列を、 raw " "string に連結します::" #: ../../faq/programming.rst:1054 msgid "" "It is also possible to use :func:`os.path.join` to append a backslash on " "Windows::" msgstr "" "Windowsでは、 :func:`os.path.join` を使ってバックスラッシュを追加することもで" "きます::" #: ../../faq/programming.rst:1059 msgid "" "Note that while a backslash will \"escape\" a quote for the purposes of " "determining where the raw string ends, no escaping occurs when interpreting " "the value of the raw string. That is, the backslash remains present in the " "value of the raw string::" msgstr "" "注意点として、バックスラッシュは raw string 終端のクォートを「エスケープ」し" "ますが、 raw string の値を解釈する際にはエスケープが生じません。つまり、バッ" "クスラッシュは raw string 値の中に残ったままになります::" #: ../../faq/programming.rst:1067 msgid "Also see the specification in the :ref:`language reference `." msgstr ":ref:`言語リファレンス ` の仕様も参照してください。" #: ../../faq/programming.rst:1070 msgid "Performance" msgstr "性能" #: ../../faq/programming.rst:1073 msgid "My program is too slow. How do I speed it up?" msgstr "プログラムが遅すぎます。どうしたら速くなりますか?" #: ../../faq/programming.rst:1075 msgid "" "That's a tough one, in general. First, here are a list of things to " "remember before diving further:" msgstr "" "これは、一般的に難しい問題です。まず、先に進む前に覚えておいて欲しいことをこ" "こに挙げます:" #: ../../faq/programming.rst:1078 msgid "" "Performance characteristics vary across Python implementations. This FAQ " "focuses on :term:`CPython`." msgstr "" "性能の傾向は Python 実装によって変わります。この FAQ では :term:`CPython` に" "焦点を当てます。" #: ../../faq/programming.rst:1080 msgid "" "Behaviour can vary across operating systems, especially when talking about I/" "O or multi-threading." msgstr "" "振る舞いはオペレーティングシステムによって変わりえます。特に、I/O やマルチス" "レッドに関しては顕著です。" #: ../../faq/programming.rst:1082 msgid "" "You should always find the hot spots in your program *before* attempting to " "optimize any code (see the :mod:`profile` module)." msgstr "" "常に、コードの最適化を始める *前に* プログラムのホットスポットを見つけるべき" "です (:mod:`profile` モジュールを参照してください)。" #: ../../faq/programming.rst:1084 msgid "" "Writing benchmark scripts will allow you to iterate quickly when searching " "for improvements (see the :mod:`timeit` module)." msgstr "" "ベンチマークスクリプトを書くことで、改善箇所の捜索を素早く繰り返せます (:mod:" "`timeit` モジュールを参照してください)。" #: ../../faq/programming.rst:1086 msgid "" "It is highly recommended to have good code coverage (through unit testing or " "any other technique) before potentially introducing regressions hidden in " "sophisticated optimizations." msgstr "" "洗練された最適化に隠れたリグレッションの可能性を生む前に、(ユニットテストやそ" "の他の技法で) コードカバレッジを上げることを強く推奨します。" #: ../../faq/programming.rst:1090 msgid "" "That being said, there are many tricks to speed up Python code. Here are " "some general principles which go a long way towards reaching acceptable " "performance levels:" msgstr "" "とは言っても、Python コードを高速化する技法はたくさんあります。ここでは、満足" "な性能のレベルにたどり着くまでの長い道のりを進む、一般的な方針を示します:" #: ../../faq/programming.rst:1094 msgid "" "Making your algorithms faster (or changing to faster ones) can yield much " "larger benefits than trying to sprinkle micro-optimization tricks all over " "your code." msgstr "" "コード中に細かい最適化の技法をばらまこうとするよりも、アルゴリズムを高速化 " "(または高速なアルゴリズムに変更) するほうが、大きな利益を生むことがあります。" #: ../../faq/programming.rst:1098 msgid "" "Use the right data structures. Study documentation for the :ref:`bltin-" "types` and the :mod:`collections` module." msgstr "" "適切なデータ構造を使ってください。:ref:`bltin-types` や :mod:`collections` を" "調べてください。" #: ../../faq/programming.rst:1101 msgid "" "When the standard library provides a primitive for doing something, it is " "likely (although not guaranteed) to be faster than any alternative you may " "come up with. This is doubly true for primitives written in C, such as " "builtins and some extension types. For example, be sure to use either the :" "meth:`list.sort` built-in method or the related :func:`sorted` function to " "do sorting (and see the :ref:`sortinghowto` for examples of moderately " "advanced usage)." msgstr "" "何かをするための基本要素が標準ライブラリにあるなら、自分で発明した代用品より" "もそちらのほうが、(絶対にとは言えませんが) おそらく速いです。\n" "それが組み込み型やある種の拡張型のように C で書かれたものならなおさらです。\n" "たとえば、ソートするには、必ず :meth:`list.sort` 組み込みメソッドか :func:" "`sorted` 関数を使ってください (また、中程度に高度な例は、 :ref:" "`sortinghowto` を参照してください)。" #: ../../faq/programming.rst:1109 msgid "" "Abstractions tend to create indirections and force the interpreter to work " "more. If the levels of indirection outweigh the amount of useful work done, " "your program will be slower. You should avoid excessive abstraction, " "especially under the form of tiny functions or methods (which are also often " "detrimental to readability)." msgstr "" "抽象化は、遠回りにしがちで、インタプリタの作業を増やすことになります。この遠" "回りさが、なされる作業の量より重大になると、プログラムが遅くなってしまいま" "す。過度な抽象化、特に細かい関数やメソッドの形で現れるもの (これは読みにくさ" "も落とします) は防ぐべきです。" #: ../../faq/programming.rst:1115 msgid "" "If you have reached the limit of what pure Python can allow, there are tools " "to take you further away. For example, `Cython `_ can " "compile a slightly modified version of Python code into a C extension, and " "can be used on many different platforms. Cython can take advantage of " "compilation (and optional type annotations) to make your code significantly " "faster than when interpreted. If you are confident in your C programming " "skills, you can also :ref:`write a C extension module ` " "yourself." msgstr "" "pure Python にできる限界に達したなら、更に進むためのツールがあります。例え" "ば、`Cython `_ は、Python コードのわずかに変形した版を C " "拡張にコンパイルし、多種のプラットフォームで使えます。Cython は、コンパイル " "(と任意の型アノテーション) を利用し、コードの解釈を大幅に速くします。C プログ" "ラミングに自信があるなら、自分で :ref:`write a C extension module ` こともできます。" #: ../../faq/programming.rst:1125 msgid "" "The wiki page devoted to `performance tips `_." msgstr "" "`パフォーマンス tips `_ が載っている wiki のページ。" #: ../../faq/programming.rst:1131 msgid "What is the most efficient way to concatenate many strings together?" msgstr "多くの文字列を結合するのに最も効率的な方法は何ですか?" #: ../../faq/programming.rst:1133 msgid "" ":class:`str` and :class:`bytes` objects are immutable, therefore " "concatenating many strings together is inefficient as each concatenation " "creates a new object. In the general case, the total runtime cost is " "quadratic in the total string length." msgstr "" ":class:`str` および :class:`bytes` オブジェクトはイミュータブルなので、多くの" "文字列の結合は結合ごとに新しいオブジェクトを作成し、効率が悪いです。\n" "一般的に、全体の実行時間のコストは文字列の長さの二乗に比例します。" #: ../../faq/programming.rst:1138 msgid "" "To accumulate many :class:`str` objects, the recommended idiom is to place " "them into a list and call :meth:`str.join` at the end::" msgstr "" "多くの :class:`str` オブジェクトを累積するのにおすすめのイディオムは、すべて" "をリストに配置してから最後に :meth:`str.join` を呼び出すことです::" #: ../../faq/programming.rst:1146 msgid "(another reasonably efficient idiom is to use :class:`io.StringIO`)" msgstr "(他の割と効率的なイディオムは、 :class:`io.StringIO` を使うことです)" #: ../../faq/programming.rst:1148 msgid "" "To accumulate many :class:`bytes` objects, the recommended idiom is to " "extend a :class:`bytearray` object using in-place concatenation (the ``+=`` " "operator)::" msgstr "" "多くの :class:`bytes` オブジェクトを累積するのにおすすめのイディオムは、 :" "class:`bytearray` オブジェクトをインプレース結合 (``+=`` 演算子) で拡張するこ" "とです::" #: ../../faq/programming.rst:1157 msgid "Sequences (Tuples/Lists)" msgstr "シーケンス(タプル/リスト)" #: ../../faq/programming.rst:1160 msgid "How do I convert between tuples and lists?" msgstr "タプル、リスト間の変更はどのようにするのですか?" #: ../../faq/programming.rst:1162 msgid "" "The type constructor ``tuple(seq)`` converts any sequence (actually, any " "iterable) into a tuple with the same items in the same order." msgstr "" "型コンストラクタ ``tuple(seq)`` はすべてのシーケンス (実際には、すべてのイテ" "ラブル) を同じ要素、同じ順序のタプルに変換します。" #: ../../faq/programming.rst:1165 msgid "" "For example, ``tuple([1, 2, 3])`` yields ``(1, 2, 3)`` and ``tuple('abc')`` " "yields ``('a', 'b', 'c')``. If the argument is a tuple, it does not make a " "copy but returns the same object, so it is cheap to call :func:`tuple` when " "you aren't sure that an object is already a tuple." msgstr "" "例えば、 ``tuple([1, 2, 3])`` は ``(1, 2, 3)`` を与え、 ``tuple('abc')`` は " "``('a', 'b', 'c')`` を与えます。引数がタプルなら、コピーを作らずに引数のオブ" "ジェクトそのものを返すので、あるオブジェクトが既にタプルになっているか確信が" "持てないのなら、 :func:`tuple` を呼ぶのが手軽です。" #: ../../faq/programming.rst:1170 msgid "" "The type constructor ``list(seq)`` converts any sequence or iterable into a " "list with the same items in the same order. For example, ``list((1, 2, " "3))`` yields ``[1, 2, 3]`` and ``list('abc')`` yields ``['a', 'b', 'c']``. " "If the argument is a list, it makes a copy just like ``seq[:]`` would." msgstr "" "型コンストラクタ ``list(seq)`` はすべてのシーケンスあるいはイテラブルを同じ要" "素、同じ順序のリストに変換します。例えば、``list((1, 2, 3))`` は ``[1, 2, " "3]`` を与え、``list('abc')`` は ``['a', 'b', 'c']`` を与えます。引数がリスト" "なら、``seq[:]`` と同様にコピーを作ります。" #: ../../faq/programming.rst:1177 msgid "What's a negative index?" msgstr "負の添え字は何ですか?" #: ../../faq/programming.rst:1179 msgid "" "Python sequences are indexed with positive numbers and negative numbers. " "For positive numbers 0 is the first index 1 is the second index and so " "forth. For negative indices -1 is the last index and -2 is the penultimate " "(next to last) index and so forth. Think of ``seq[-n]`` as the same as " "``seq[len(seq)-n]``." msgstr "" "Python のシーケンスは正の数と負の数でインデクスされます。正の数では、0 が最初" "のインデクス、1 が 2 番目のインデクス、以下も同様です。負のインデクスで" "は、-1 が最後のインデクス、-2 が最後から 2 番目のインデクス、以下も同様です。" "``seq[-n]`` は ``seq[len(seq)-n]`` と同じだと考えてください。" #: ../../faq/programming.rst:1184 msgid "" "Using negative indices can be very convenient. For example ``S[:-1]`` is " "all of the string except for its last character, which is useful for " "removing the trailing newline from a string." msgstr "" "負のインデクスを使うと便利なことがあります。例えば、``S[:-1]`` は文字列の最後" "以外のすべての文字を表すので、文字列の末尾の改行を取り除くときに便利です。" #: ../../faq/programming.rst:1190 msgid "How do I iterate over a sequence in reverse order?" msgstr "シーケンスを逆順にイテレートするにはどうしたらいいですか?" #: ../../faq/programming.rst:1192 msgid "Use the :func:`reversed` built-in function::" msgstr "組み込み関数 :func:`reversed` を使ってください。" #: ../../faq/programming.rst:1197 msgid "" "This won't touch your original sequence, but build a new copy with reversed " "order to iterate over." msgstr "" "これは元のシーケンスをいじるのではなく、逆順の新しいコピーを作ってイテレート" "させます。" #: ../../faq/programming.rst:1202 msgid "How do you remove duplicates from a list?" msgstr "リストから重複を取り除くにはどうしますか?" #: ../../faq/programming.rst:1204 msgid "See the Python Cookbook for a long discussion of many ways to do this:" msgstr "Python Cookbook の長い議論に多くの方法があるので参照してください:" #: ../../faq/programming.rst:1206 msgid "https://code.activestate.com/recipes/52560/" msgstr "https://code.activestate.com/recipes/52560/" #: ../../faq/programming.rst:1208 msgid "" "If you don't mind reordering the list, sort it and then scan from the end of " "the list, deleting duplicates as you go::" msgstr "" "リストを並び替えて構わないのなら、ソートした上でリストの最初から最後までを調" "べ、次のように重複を削除してください::" #: ../../faq/programming.rst:1220 msgid "" "If all elements of the list may be used as set keys (i.e. they are all :term:" "`hashable`) this is often faster ::" msgstr "" "リストのすべての要素が集合のキーとして使える (つまり、すべての要素が :term:" "`hashable`) なら、おそらくこのほうが速いです ::" #: ../../faq/programming.rst:1225 msgid "" "This converts the list into a set, thereby removing duplicates, and then " "back into a list." msgstr "" "リストを集合に変換するときに重複は取り除かれるので、それをリストに戻せばいい" "のです。" #: ../../faq/programming.rst:1230 msgid "How do you remove multiple items from a list" msgstr "リストから複数のアイテムを取り除く方法" #: ../../faq/programming.rst:1232 msgid "" "As with removing duplicates, explicitly iterating in reverse with a delete " "condition is one possibility. However, it is easier and faster to use slice " "replacement with an implicit or explicit forward iteration. Here are three " "variations.::" msgstr "" "重複除去と同様に、削除条件を付けて明示的に逆回すのも一つの方法です。ですが、" "明示的/暗黙的な反復でスライス置換する方が速くて簡単です。こちらは3つのバリ" "エーションです。::" #: ../../faq/programming.rst:1241 msgid "The list comprehension may be fastest." msgstr "リスト内包表記がおそらく最も高速です。" #: ../../faq/programming.rst:1245 msgid "How do you make an array in Python?" msgstr "Python で配列を作るにはどうしますか?" #: ../../faq/programming.rst:1247 msgid "Use a list::" msgstr "リストを使ってください::" #: ../../faq/programming.rst:1251 msgid "" "Lists are equivalent to C or Pascal arrays in their time complexity; the " "primary difference is that a Python list can contain objects of many " "different types." msgstr "" "リストの時間計算量は C や Pascal の配列と同じです。大きな違いは、Python のリ" "ストは多くの異なる型のオブジェクトを含めることです。" #: ../../faq/programming.rst:1254 msgid "" "The ``array`` module also provides methods for creating arrays of fixed " "types with compact representations, but they are slower to index than " "lists. Also note that `NumPy `_ and other third party " "packages define array-like structures with various characteristics as well." msgstr "" "``array`` モジュールにも固定された型を簡潔に表現する配列を作るためのメソッド" "がありますが、リストよりもインデクスが遅いです。また、`NumPy `_ やその他のサードパーティー拡張でも、様々な特徴をもつ配列的な構造体が" "定義されています。" #: ../../faq/programming.rst:1260 msgid "" "To get Lisp-style linked lists, you can emulate *cons cells* using tuples::" msgstr "" "Lisp 方式の連結リストを得るのに、タプルを使って *cons cells* をエミュレートで" "きます::" #: ../../faq/programming.rst:1264 msgid "" "If mutability is desired, you could use lists instead of tuples. Here the " "analogue of a Lisp *car* is ``lisp_list[0]`` and the analogue of *cdr* is " "``lisp_list[1]``. Only do this if you're sure you really need to, because " "it's usually a lot slower than using Python lists." msgstr "" "ミュータブルな必要があるなら、タプルではなくリストを使いましょう。Lisp の " "*car* にあたるものが ``lisp_list[0]`` で、cdr にあたるものが " "``lisp_list[1]`` です。本当に必要だと確信できるとき以外はこれはしないでくださ" "い。たいてい、これは Python のリストを使うよりも非常に遅いですから。" #: ../../faq/programming.rst:1273 msgid "How do I create a multidimensional list?" msgstr "多次元のリストを作るにはどうしますか?" #: ../../faq/programming.rst:1275 msgid "You probably tried to make a multidimensional array like this::" msgstr "このようにして多次元の配列を作ろうとしてしまったことがあるでしょう::" #: ../../faq/programming.rst:1279 msgid "This looks correct if you print it:" msgstr "これを表示したときには問題なさそうに見えます:" #: ../../faq/programming.rst:1290 msgid "But when you assign a value, it shows up in multiple places:" msgstr "しかし値を代入すると、その値が複数の場所に現れてしまいます:" #: ../../faq/programming.rst:1302 msgid "" "The reason is that replicating a list with ``*`` doesn't create copies, it " "only creates references to the existing objects. The ``*3`` creates a list " "containing 3 references to the same list of length two. Changes to one row " "will show in all rows, which is almost certainly not what you want." msgstr "" "これは、``*`` を使ったリストの複製がコピーを作らず、存在するオブジェクトへの" "参照を作るだけだからです。この ``*3`` は長さ 2 の同じリストへの参照を含むリス" "トを作ります。一つの列に対する変更はすべての列に現れますが、これが望んだ結果" "であることはまずないでしょう。" #: ../../faq/programming.rst:1307 msgid "" "The suggested approach is to create a list of the desired length first and " "then fill in each element with a newly created list::" msgstr "" "おすすめの方法は、最初に望んだ長さのリストを作り、それから新しく作ったリスト" "でそれぞれの要素を埋めていくことです::" #: ../../faq/programming.rst:1314 msgid "" "This generates a list containing 3 different lists of length two. You can " "also use a list comprehension::" msgstr "" "これは長さ 2 の異なるリスト 3 つを含むリストを生成します。リスト内包表記も使" "えます::" #: ../../faq/programming.rst:1320 msgid "" "Or, you can use an extension that provides a matrix datatype; `NumPy " "`_ is the best known." msgstr "" "あるいは、行列データ型を提供している拡張を使用することもできます; `NumPy " "`_ が最もよく知られています。" #: ../../faq/programming.rst:1325 msgid "How do I apply a method to a sequence of objects?" msgstr "オブジェクトのシーケンスにメソッドを適用するにはどうしますか?" #: ../../faq/programming.rst:1327 msgid "Use a list comprehension::" msgstr "リスト内包表記を使ってください::" #: ../../faq/programming.rst:1334 msgid "" "Why does a_tuple[i] += ['item'] raise an exception when the addition works?" msgstr "なぜ加算はされるのに a_tuple[i] += ['item'] は例外を送出するのですか?" #: ../../faq/programming.rst:1336 msgid "" "This is because of a combination of the fact that augmented assignment " "operators are *assignment* operators, and the difference between mutable and " "immutable objects in Python." msgstr "" "これは、累算代入演算子は *代入* 演算子だ、という事実と、Python での可変オブ" "ジェクトと不変オブジェクトの違いが組み合わさって起きるのです。" #: ../../faq/programming.rst:1340 msgid "" "This discussion applies in general when augmented assignment operators are " "applied to elements of a tuple that point to mutable objects, but we'll use " "a ``list`` and ``+=`` as our exemplar." msgstr "" "この議論は一般的に、可変オブジェクトを指すタプルの要素に、累算代入演算子が適" "用されたときにも適用できますが、例として ``list`` と ``+=`` を使います。" #: ../../faq/programming.rst:1344 msgid "If you wrote::" msgstr "次のように書いたとします::" #: ../../faq/programming.rst:1352 msgid "" "The reason for the exception should be immediately clear: ``1`` is added to " "the object ``a_tuple[0]`` points to (``1``), producing the result object, " "``2``, but when we attempt to assign the result of the computation, ``2``, " "to element ``0`` of the tuple, we get an error because we can't change what " "an element of a tuple points to." msgstr "" "例外が送出された理由は明らかです: ``1`` が (``1``) を指すオブジェクト " "``a_tuple[0]`` に加えられ、結果のオブジェクト ``2`` が生成されますが、計算結" "果 ``2`` をタプルの第 ``0`` 要素に代入しようとしたときに、エラーが発生しま" "す。なぜならば、タプルの要素が何を指すかは変えられないからです。" #: ../../faq/programming.rst:1358 msgid "" "Under the covers, what this augmented assignment statement is doing is " "approximately this::" msgstr "このような裏事情の元、累算代入文はだいたい次のようなことをしています::" #: ../../faq/programming.rst:1367 msgid "" "It is the assignment part of the operation that produces the error, since a " "tuple is immutable." msgstr "タプルは不変なので、例外を生み出しているのは操作の代入部分なのです。" #: ../../faq/programming.rst:1370 msgid "When you write something like::" msgstr "次のように書いたとします::" #: ../../faq/programming.rst:1378 msgid "" "The exception is a bit more surprising, and even more surprising is the fact " "that even though there was an error, the append worked::" msgstr "" "この例外にはちょっと驚きますが、もっと驚くべきことは、エラーがあったとしても" "追記はきちんと動いている、という事実です::" #: ../../faq/programming.rst:1384 msgid "" "To see why this happens, you need to know that (a) if an object implements " "an :meth:`~object.__iadd__` magic method, it gets called when the ``+=`` " "augmented assignment is executed, and its return value is what gets used in " "the assignment statement; and (b) for lists, :meth:`!__iadd__` is equivalent " "to calling :meth:`~list.extend` on the list and returning the list. That's " "why we say that for lists, ``+=`` is a \"shorthand\" for :meth:`!list." "extend`::" msgstr "" "なぜこれが起きるかを調べるためには、次の 2 点を知っている必要があります。(a) " "オブジェクトに :meth:`~object.__iadd__` 特殊メソッドが実装されている場合、拡" "張代入 ``+=`` が実行されるときにそれが呼び出され、その返り値が代入文で使われ" "ます; (b) リストでは、:meth:`!__iadd__` は :meth:`~list.extend` の呼び出しと" "等価で、リストを返します。こんな理由で、リストでは ``+=`` は :meth:`!list." "extend` の \"略記\" だと言ったのでした::" #: ../../faq/programming.rst:1397 msgid "This is equivalent to::" msgstr "これは次と等価です::" #: ../../faq/programming.rst:1402 msgid "" "The object pointed to by a_list has been mutated, and the pointer to the " "mutated object is assigned back to ``a_list``. The end result of the " "assignment is a no-op, since it is a pointer to the same object that " "``a_list`` was previously pointing to, but the assignment still happens." msgstr "" "a_list が指していたオブジェクトは更新され、更新されたオブジェクトへのポインタ" "は再度 ``a_list`` に代入されます。代入しているのは、``a_list`` が更新前まで指" "していた同じオブジェクトへのポインタなので、代入は最終的には何もしていないの" "ですが、代入処理自体は起きています。" #: ../../faq/programming.rst:1407 msgid "Thus, in our tuple example what is happening is equivalent to::" msgstr "従って、今のタプルの例では、次のと同じことが起きています::" #: ../../faq/programming.rst:1415 msgid "" "The :meth:`!__iadd__` succeeds, and thus the list is extended, but even " "though ``result`` points to the same object that ``a_tuple[0]`` already " "points to, that final assignment still results in an error, because tuples " "are immutable." msgstr "" ":meth:`!__iadd__` は成功し、リストは拡張 (extend) されますが、``result`` が " "``a_tuple[0]`` が既に指しているオブジェクトと同じオブジェクトを指していたとし" "ても、タプルは不変なので、その最後の代入はやはりエラーとなります。" #: ../../faq/programming.rst:1421 msgid "" "I want to do a complicated sort: can you do a Schwartzian Transform in " "Python?" msgstr "複雑なソートがしたいのですが、Python でシュワルツ変換はできますか?" #: ../../faq/programming.rst:1423 msgid "" "The technique, attributed to Randal Schwartz of the Perl community, sorts " "the elements of a list by a metric which maps each element to its \"sort " "value\". In Python, use the ``key`` argument for the :meth:`list.sort` " "method::" msgstr "" "Perl コミュニティの Randal Schwartz の作とされるこのテクニックは、リストの要" "素を、それぞれの要素をその「ソート値」に対応付けるメトリックによってソートし" "ます。Python では、 :meth:`list.sort` メソッドに ``key`` 引数を使ってくださ" "い::" #: ../../faq/programming.rst:1432 msgid "How can I sort one list by values from another list?" msgstr "リストを別のリストの値によってソートするにはどうしますか?" #: ../../faq/programming.rst:1434 msgid "" "Merge them into an iterator of tuples, sort the resulting list, and then " "pick out the element you want. ::" msgstr "" "二つのイテレータを混ぜあわせてタプルのイテレータにしてから、必要な要素を選ん" "でください。 ::" #: ../../faq/programming.rst:1449 msgid "Objects" msgstr "オブジェクト" #: ../../faq/programming.rst:1452 msgid "What is a class?" msgstr "クラスとは何ですか?" #: ../../faq/programming.rst:1454 msgid "" "A class is the particular object type created by executing a class " "statement. Class objects are used as templates to create instance objects, " "which embody both the data (attributes) and code (methods) specific to a " "datatype." msgstr "" "クラスは、class 文の実行で生成される特殊なオブジェクトです。クラスオブジェク" "トはインスタンスオブジェクトを生成するためのテンプレートとして使われ、ある" "データ型に特有のデータ (attribute/属性) とコード (メソッド) の両方を内蔵して" "います。" #: ../../faq/programming.rst:1458 msgid "" "A class can be based on one or more other classes, called its base " "class(es). It then inherits the attributes and methods of its base classes. " "This allows an object model to be successively refined by inheritance. You " "might have a generic ``Mailbox`` class that provides basic accessor methods " "for a mailbox, and subclasses such as ``MboxMailbox``, ``MaildirMailbox``, " "``OutlookMailbox`` that handle various specific mailbox formats." msgstr "" "新しいクラスを一つ以上の他のクラス (新しいクラスの基底クラスと呼ばれます) に" "基づいて作ることもできます。この新しいクラスは、基底クラスから属性とメソッド" "を継承します。これにより、オブジェクトモデルを継承で連続的に洗練できます。" "メールボックスへの基本的なアクセサを提供する一般的な ``Mailbox`` クラスを作っ" "て、それからいろいろな特定のメールボックスの形式を扱う ``MboxMailbox``、" "``MaildirMailbox``、``OutlookMailbox`` のようなサブクラスを作れるのです。" #: ../../faq/programming.rst:1467 msgid "What is a method?" msgstr "メソッドとは何ですか?" #: ../../faq/programming.rst:1469 msgid "" "A method is a function on some object ``x`` that you normally call as ``x." "name(arguments...)``. Methods are defined as functions inside the class " "definition::" msgstr "" "メソッドは、オブジェクト ``x`` が持つ関数で、通常 ``x.name(arguments...)`` と" "して呼び出されるものです。メソッドはクラス定義の中で関数として定義されます::" #: ../../faq/programming.rst:1479 msgid "What is self?" msgstr "self とは何ですか?" #: ../../faq/programming.rst:1481 msgid "" "Self is merely a conventional name for the first argument of a method. A " "method defined as ``meth(self, a, b, c)`` should be called as ``x.meth(a, b, " "c)`` for some instance ``x`` of the class in which the definition occurs; " "the called method will think it is called as ``meth(x, a, b, c)``." msgstr "" "self はメソッドの第一引数に慣習的につけられる名前にすぎません。``meth(self, " "a, b, c)`` として定義されたメソッドは、その定義がなされたクラスのインスタン" "ス ``x`` に対して ``x.meth(a, b, c)`` として呼び出されます。呼び出されたメ" "ソッドは、``meth(x, a, b, c)`` が呼ばれたものと考えます。" #: ../../faq/programming.rst:1486 msgid "See also :ref:`why-self`." msgstr ":ref:`why-self` も参照してください。" #: ../../faq/programming.rst:1490 msgid "" "How do I check if an object is an instance of a given class or of a subclass " "of it?" msgstr "" "あるオブジェクトが、与えられたクラスやそのサブクラスのインスタンスであるかを" "調べるにはどうしますか?" #: ../../faq/programming.rst:1492 msgid "" "Use the built-in function :func:`isinstance(obj, cls) `. You " "can check if an object is an instance of any of a number of classes by " "providing a tuple instead of a single class, e.g. ``isinstance(obj, (class1, " "class2, ...))``, and can also check whether an object is one of Python's " "built-in types, e.g. ``isinstance(obj, str)`` or ``isinstance(obj, (int, " "float, complex))``." msgstr "" "ビルトイン関数 :func:`isinstance(obj, cls) ` を使ってください。ク" "ラスのタプルを与えて ``isinstance(obj, (class1, class2, ...))`` のようにすれ" "ば、あるオブジェクトが任意の数のクラスのオブジェクトであるかを調べられます" "し、``isinstance(obj, str)`` や ``isinstance(obj, (int, float, complex))`` の" "ようにすれば、Python のビルトイン型のオブジェクトであるかも調べられます。" #: ../../faq/programming.rst:1499 msgid "" "Note that :func:`isinstance` also checks for virtual inheritance from an :" "term:`abstract base class`. So, the test will return ``True`` for a " "registered class even if hasn't directly or indirectly inherited from it. " "To test for \"true inheritance\", scan the :term:`MRO` of the class:" msgstr "" "注意: :func:`isinstance` は :term:`abstract base class` (抽象基底クラス)から" "の仮想継承もチェックします。そのため、登録 (register) されたクラスが直接/間接" "的にそれを継承していなくても ``True`` を返します。「真のインスタンス」をテス" "トする場合は、クラスの :term:`MRO` を調べます:" #: ../../faq/programming.rst:1534 msgid "" "Note that most programs do not use :func:`isinstance` on user-defined " "classes very often. If you are developing the classes yourself, a more " "proper object-oriented style is to define methods on the classes that " "encapsulate a particular behaviour, instead of checking the object's class " "and doing a different thing based on what class it is. For example, if you " "have a function that does something::" msgstr "" "なお、大部分のプログラムでは、 :func:`isinstance` をユーザー定義のクラスに何" "度も使うべきではありません。クラスを自分で開発するときに、適切なオブジェクト" "指向スタイルは、特定の振る舞いをカプセル化するクラスのメソッドを定義するもの" "であって、オブジェクトのクラスを調べてそのクラスに応じて違うことをするもので" "はありません。例えば、何かをする関数があったとして::" #: ../../faq/programming.rst:1548 msgid "" "A better approach is to define a ``search()`` method on all the classes and " "just call it::" msgstr "" "よりよいアプローチは、``search()`` メソッドをすべてのクラスに定義して、それを" "ただ呼び出すことです::" #: ../../faq/programming.rst:1563 msgid "What is delegation?" msgstr "委譲とは何ですか?" #: ../../faq/programming.rst:1565 msgid "" "Delegation is an object oriented technique (also called a design pattern). " "Let's say you have an object ``x`` and want to change the behaviour of just " "one of its methods. You can create a new class that provides a new " "implementation of the method you're interested in changing and delegates all " "other methods to the corresponding method of ``x``." msgstr "" "委譲 (delegation) とは、オブジェクト指向のテクニック (デザインパターンとも呼" "ばれる) の一つです。オブジェクト ``x`` があって、そのメソッドのうちただ一つの" "振る舞いを変えたいとしましょう。新しいクラスを作成し、変えたいメソッドだけを" "新しく実装し、他のすべてのメソッドを ``x`` の対応するメソッドに委譲する新しい" "クラスを作れます。" #: ../../faq/programming.rst:1571 msgid "" "Python programmers can easily implement delegation. For example, the " "following class implements a class that behaves like a file but converts all " "written data to uppercase::" msgstr "" "Python プログラマは簡単に委譲を実装できます。例えば、以下のクラスは、ファイル" "のように振る舞いながらすべての文字を大文字に変換するクラスを実装します::" #: ../../faq/programming.rst:1586 msgid "" "Here the ``UpperOut`` class redefines the ``write()`` method to convert the " "argument string to uppercase before calling the underlying ``self._outfile." "write()`` method. All other methods are delegated to the underlying ``self." "_outfile`` object. The delegation is accomplished via the :meth:`~object." "__getattr__` method; consult :ref:`the language reference ` for more information about controlling attribute access." msgstr "" "ここで ``UpperOut`` クラスは ``write()`` メソッドを定義しなおして、引数の文字" "列を大文字に変換してから基礎となる ``self._outfile.write()`` メソッドを呼び出" "すようにします。その他すべてのメソッドは基礎となる ``self._outfile`` オブジェ" "クトに移譲されます。この委譲は :meth:`~object.__getattr__` メソッドを通してな" "されます。属性の制御の詳細は :ref:`言語リファレンス ` を参" "照してください。" #: ../../faq/programming.rst:1593 msgid "" "Note that for more general cases delegation can get trickier. When " "attributes must be set as well as retrieved, the class must define a :meth:" "`~object.__setattr__` method too, and it must do so carefully. The basic " "implementation of :meth:`!__setattr__` is roughly equivalent to the " "following::" msgstr "" "なお、一般的に委譲はトリッキーになりがちです。属性が設定される時には読み出さ" "れる時と同様に、そのクラスに :meth:`~object.__setattr__` メソッドを定義する必" "要があり、それには細心の注意が必要です。 :meth:`!__setattr__` の基本的な実装" "はおおよそ以下のようになります::" #: ../../faq/programming.rst:1604 msgid "" "Most :meth:`!__setattr__` implementations must modify :meth:`self.__dict__ " "` to store local state for self without causing an infinite " "recursion." msgstr "" "たいてい、 :meth:`!__setattr__` 実装は :meth:`self.__dict__ ` を変更して、無限再帰を起こすことなくローカルな状態を保存するように" "しなければなりません。" #: ../../faq/programming.rst:1610 msgid "" "How do I call a method defined in a base class from a derived class that " "extends it?" msgstr "" "基底クラスで定義されたメソッドを、そのクラスを継承した派生クラスから呼び出す" "にはどうしますか?" #: ../../faq/programming.rst:1612 msgid "Use the built-in :func:`super` function::" msgstr "組み込みの :func:`super` 関数を使ってください::" #: ../../faq/programming.rst:1618 msgid "" "In the example, :func:`super` will automatically determine the instance from " "which it was called (the ``self`` value), look up the :term:`method " "resolution order` (MRO) with ``type(self).__mro__``, and return the next in " "line after ``Derived`` in the MRO: ``Base``." msgstr "" "この例では、 :func:`super` は呼ばれたインスタンス (``self`` の値) を自動判断" "し、 ``type(self).__mro__`` で :term:`method resolution order` (MRO メソッド" "解決順) を検索し、そしてMRO内で ``Derived`` の次行を返します: ``Base`` 。" #: ../../faq/programming.rst:1625 msgid "How can I organize my code to make it easier to change the base class?" msgstr "基底クラスの名前を変えやすいコードを書くにはどうしますか?" #: ../../faq/programming.rst:1627 msgid "" "You could assign the base class to an alias and derive from the alias. Then " "all you have to change is the value assigned to the alias. Incidentally, " "this trick is also handy if you want to decide dynamically (e.g. depending " "on availability of resources) which base class to use. Example::" msgstr "" "基底クラスをエイリアス (alias) に代入しておいてから、そのエイリアスを継承する" "といいかもしれません。そうすればエイリアスに代入する値を変えるだけで済みま" "す。ちなみに、この手法は使用する基底クラスを動的に選びたいとき、例えば使える" "リソースによって選びたいときなどにも便利です。例::" #: ../../faq/programming.rst:1642 msgid "How do I create static class data and static class methods?" msgstr "静的なクラスデータや静的なクラスメソッドを作るにはどうしますか?" #: ../../faq/programming.rst:1644 msgid "" "Both static data and static methods (in the sense of C++ or Java) are " "supported in Python." msgstr "" "(C++ や Java の意味で) 静的なデータも静的なメソッドも Python でサポートされて" "います。" #: ../../faq/programming.rst:1647 msgid "" "For static data, simply define a class attribute. To assign a new value to " "the attribute, you have to explicitly use the class name in the assignment::" msgstr "" "静的なデータを作るには、単純にクラス属性を定義してください。その属性に新しい" "値を代入するには、代入するクラス名を明示する必要があります::" #: ../../faq/programming.rst:1659 msgid "" "``c.count`` also refers to ``C.count`` for any ``c`` such that " "``isinstance(c, C)`` holds, unless overridden by ``c`` itself or by some " "class on the base-class search path from ``c.__class__`` back to ``C``." msgstr "" "``c`` そのものや ``c.__class__`` から ``C`` にいたるパス探索経路上のクラスに" "よってオーバーライドされない限り、``c.count`` も ``isinstance(c, C)`` である" "すべての ``c`` に対する ``C.count`` を参照します。" #: ../../faq/programming.rst:1663 msgid "" "Caution: within a method of C, an assignment like ``self.count = 42`` " "creates a new and unrelated instance named \"count\" in ``self``'s own " "dict. Rebinding of a class-static data name must always specify the class " "whether inside a method or not::" msgstr "" "注意: C のメソッド内では、``self.count = 42`` のような代入は ``self`` 自身の" "辞書に \"count\" という名前の新しくて関係ないインスタンスを作ります。クラスの" "静的なデータの再束縛には、メソッド内であるか否かにかかわらず、いつもクラスを" "指定しなければなりません::" #: ../../faq/programming.rst:1670 msgid "Static methods are possible::" msgstr "静的メソッドが使えます::" #: ../../faq/programming.rst:1678 msgid "" "However, a far more straightforward way to get the effect of a static method " "is via a simple module-level function::" msgstr "" "しかし、静的メソッドの効果を得るもっと簡単な方法は、単にモジュールレベル関数" "を使うことです::" #: ../../faq/programming.rst:1684 msgid "" "If your code is structured so as to define one class (or tightly related " "class hierarchy) per module, this supplies the desired encapsulation." msgstr "" "モジュールあたりに一つのクラスを定義するように (あるいはクラス組織を厳密に関" "連させるように) コードが構成されているなら、これで必要なカプセル化ができま" "す。" #: ../../faq/programming.rst:1689 msgid "How can I overload constructors (or methods) in Python?" msgstr "" "Python でコンストラクタ(やメソッド)をオーバーロードするにはどうしたらいいです" "か?" #: ../../faq/programming.rst:1691 msgid "" "This answer actually applies to all methods, but the question usually comes " "up first in the context of constructors." msgstr "" "この質問の答えはすべてのメソッドについて言えることですが、この質問はだいたい" "以下の構造の文脈から出てきます。" #: ../../faq/programming.rst:1694 msgid "In C++ you'd write" msgstr "C++ では、このように書けます" #: ../../faq/programming.rst:1703 msgid "" "In Python you have to write a single constructor that catches all cases " "using default arguments. For example::" msgstr "" "Python では、一つのコンストラクタでデフォルトの引数を使ってすべての場合に対応" "するように書かなければなりません。例えば::" #: ../../faq/programming.rst:1713 msgid "This is not entirely equivalent, but close enough in practice." msgstr "これで完全に等価とは言えませんが、実用上は十分に近いです。" #: ../../faq/programming.rst:1715 msgid "You could also try a variable-length argument list, e.g. ::" msgstr "長さが変えられる引数のリストを試すには、例えば ::" #: ../../faq/programming.rst:1720 msgid "The same approach works for all method definitions." msgstr "これと同じやり方がすべてのメソッド定義で使えます。" #: ../../faq/programming.rst:1724 msgid "I try to use __spam and I get an error about _SomeClassName__spam." msgstr "__spam を使おうとしたら _SomeClassName__spam からエラーがでました。" #: ../../faq/programming.rst:1726 msgid "" "Variable names with double leading underscores are \"mangled\" to provide a " "simple but effective way to define class private variables. 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 any leading underscores " "stripped." msgstr "" "先頭にアンダースコアが二つ付いた変数名は、クラスのプライベートな変数を、 \"マ" "ングル化\" という単純かつ効率のいい方法で定義します。``__spam`` のような形式 " "(先頭に二つ以上、末尾にもしあっても一つのアンダースコアがある) のすべての識別" "子は、``classname`` が先頭のアンダースコアをすべて削除した現在のクラス名とす" "れば、``_classname__spam`` のように文字上で置換えられます。" #: ../../faq/programming.rst:1732 msgid "" "This doesn't guarantee privacy: an outside user can still deliberately " "access the \"_classname__spam\" attribute, and private values are visible in " "the object's ``__dict__``. Many Python programmers never bother to use " "private variable names at all." msgstr "" "これはプライベートであることを保証するものではありません。これでも外部のユー" "ザが \"_classname__spam\" 属性に直接アクセスできますし、プライベートな変数は" "オブジェクトの ``__dict__`` から見えます。多くの Python プログラマはわざわざ" "プライベートな変数名を使おうとなど考えません。" #: ../../faq/programming.rst:1739 msgid "My class defines __del__ but it is not called when I delete the object." msgstr "" "クラスに __del__ メソッドを定義しているのですが、オブジェクトを削除したときに" "呼ばれません。" #: ../../faq/programming.rst:1741 msgid "There are several possible reasons for this." msgstr "いくつかの可能性があります。" #: ../../faq/programming.rst:1743 msgid "" "The :keyword:`del` statement does not necessarily call :meth:`~object." "__del__` -- it simply decrements the object's reference count, and if this " "reaches zero :meth:`!__del__` is called." msgstr "" ":keyword:`del` 文は必ずしも :meth:`~object.__del__` を呼び出すとは限りません " "-- これは単純にオブジェクトの参照カウントを減らすもので、カウントがゼロになっ" "たときに :meth:`!__del__` が呼び出されます。" #: ../../faq/programming.rst:1747 msgid "" "If your data structures contain circular links (e.g. a tree where each child " "has a parent reference and each parent has a list of children) the reference " "counts will never go back to zero. Once in a while Python runs an algorithm " "to detect such cycles, but the garbage collector might run some time after " "the last reference to your data structure vanishes, so your :meth:`!__del__` " "method may be called at an inconvenient and random time. This is " "inconvenient if you're trying to reproduce a problem. Worse, the order in " "which object's :meth:`!__del__` methods are executed is arbitrary. You can " "run :func:`gc.collect` to force a collection, but there *are* pathological " "cases where objects will never be collected." msgstr "" "データ構造が循環リンク (子のそれぞれが親の参照を持ち、親のそれぞれが子のリス" "トを持つツリーなど) を含む場合、その参照カウントは決して 0 にはなりません。" "時々、Python はこのようなサイクルを検出するアルゴリズムを実行しますが、データ" "構造への参照がなくなってからこのガベージコレクタが実行されるまでいくらか時間" "が掛かるかもしれないので、 :meth:`!__del__` メソッドは不都合な予期できないタ" "イミングで呼び出されるかもしれません。これは問題を再現しようとするときに不便" "です。さらに悪いことに、オブジェクトの :meth:`!__del__` メソッドが実行される" "順序は任意です。 :func:`gc.collect` を起動して収集を強制することができます" "が、オブジェクトが決して回収されないような本当に病的な場合も *あります* 。" #: ../../faq/programming.rst:1758 msgid "" "Despite the cycle collector, it's still a good idea to define an explicit " "``close()`` method on objects to be called whenever you're done with them. " "The ``close()`` method can then remove attributes that refer to subobjects. " "Don't call :meth:`!__del__` directly -- :meth:`!__del__` should call " "``close()`` and ``close()`` should make sure that it can be called more than " "once for the same object." msgstr "" "循環参照コレクタがあるとはいえ、オブジェクトに ``close()`` メソッドを明示的に" "定義し、使い終わったらいつでも呼び出せるようにするのはいいことです。\n" "``close()`` メソッドを使うと、サブオブジェクトを参照している属性を取り除けま" "す。\n" ":meth:`!__del__` を直接呼び出さないでください -- :meth:`!__del__` は " "``close()`` を呼び出すでしょうし、 ``close()`` なら同じオブジェクトに対して複" "数回呼ばれてもいいことが保証されているでしょう。" #: ../../faq/programming.rst:1765 msgid "" "Another way to avoid cyclical references is to use the :mod:`weakref` " "module, which allows you to point to objects without incrementing their " "reference count. Tree data structures, for instance, should use weak " "references for their parent and sibling references (if they need them!)." msgstr "" "循環参照を避ける他の方法は、 :mod:`weakref` モジュールを使って、参照カウント" "を増やすことなくオブジェクトを示すことです。例えばツリー構造は、親と (必要な" "ら!) 兄弟に弱参照を使うべきです。" #: ../../faq/programming.rst:1778 msgid "" "Finally, if your :meth:`!__del__` method raises an exception, a warning " "message is printed to :data:`sys.stderr`." msgstr "" "最後に、 :meth:`!__del__` メソッドが例外を発生させた場合、警告のメッセージ" "が :data:`sys.stderr` に書きこまれます。" #: ../../faq/programming.rst:1783 msgid "How do I get a list of all instances of a given class?" msgstr "与えられたクラスのすべてのインスタンスのリストを得るにはどうしますか?" #: ../../faq/programming.rst:1785 msgid "" "Python does not keep track of all instances of a class (or of a built-in " "type). You can program the class's constructor to keep track of all " "instances by keeping a list of weak references to each instance." msgstr "" "Python はクラス (やビルトイン型) のすべてのインスタンスをたどりません。クラス" "のコンストラクタにそれぞれのインスタンスへの弱参照のリストを作らせることです" "べてのインスタンスをたどらせられます。" #: ../../faq/programming.rst:1791 msgid "Why does the result of ``id()`` appear to be not unique?" msgstr "なぜ ``id()`` の結果は一意でないように見えるのですか?" #: ../../faq/programming.rst:1793 msgid "" "The :func:`id` builtin returns an integer that is guaranteed to be unique " "during the lifetime of the object. Since in CPython, this is the object's " "memory address, it happens frequently that after an object is deleted from " "memory, the next freshly created object is allocated at the same position in " "memory. This is illustrated by this example:" msgstr "" "組み込みの :func:`id` は、オブジェクトが生存している間は一意なことが保証され" "ている整数値を返します。 CPython では、それはオブジェクトのメモリアドレスなの" "で、オブジェクトがメモリから削除された後に、次に新しく生成されたオブジェクト" "はメモリの同じ場所にメモリ領域を確保されていることが、しばしば起きます。この" "現象を次の例で示しましょう:" #: ../../faq/programming.rst:1804 msgid "" "The two ids belong to different integer objects that are created before, and " "deleted immediately after execution of the ``id()`` call. To be sure that " "objects whose id you want to examine are still alive, create another " "reference to the object:" msgstr "" "2 つの同じ値を持つ id は ``id()`` の実行の前に作られてすぐさま削除された異な" "る整数オブジェクトによるものです。id を調べたいオブジェクトがまだ生きてること" "を保証したいなら、オブジェクトへの別の参照を作ってください:" #: ../../faq/programming.rst:1817 msgid "When can I rely on identity tests with the *is* operator?" msgstr "いつ *is* 演算子での同一性テストが頼れますか?" #: ../../faq/programming.rst:1819 msgid "" "The ``is`` operator tests for object identity. The test ``a is b`` is " "equivalent to ``id(a) == id(b)``." msgstr "" "``is`` 演算子はオブジェクトの同一性をテストします。 テスト ``a is b`` は " "``id(a) == id(b)`` と同等です。" #: ../../faq/programming.rst:1822 msgid "" "The most important property of an identity test is that an object is always " "identical to itself, ``a is a`` always returns ``True``. Identity tests are " "usually faster than equality tests. And unlike equality tests, identity " "tests are guaranteed to return a boolean ``True`` or ``False``." msgstr "" "同一性テストの最も重要な特性は、オブジェクトは常にそれ自身と同一であり、 ``a " "is a`` は常に ``True`` を返すということです。 同一性テストは通常、等価性テス" "トよりも高速です。 また、等価性テストとは異なり、同一性テストは真偽値 " "``True`` または``False`` を返すことが保証されています。" #: ../../faq/programming.rst:1827 msgid "" "However, identity tests can *only* be substituted for equality tests when " "object identity is assured. Generally, there are three circumstances where " "identity is guaranteed:" msgstr "" "ただし、同一性テストを等価性テストの代用とできるのは、オブジェクトの同一性が" "保証されている場合 *のみ* です。 一般的に、同一性が保証される状況は3つありま" "す:" #: ../../faq/programming.rst:1831 msgid "" "1) Assignments create new names but do not change object identity. After " "the assignment ``new = old``, it is guaranteed that ``new is old``." msgstr "" "1) 代入は新しい名前を作りますが、オブジェクトIDは変えません。 ``new = " "old`` 代入の後、 ``new is old`` が保証されます。" #: ../../faq/programming.rst:1834 msgid "" "2) Putting an object in a container that stores object references does not " "change object identity. After the list assignment ``s[0] = x``, it is " "guaranteed that ``s[0] is x``." msgstr "" "2) オブジェクト参照を格納するコンテナにオブジェクトを入れても、オブジェクト" "IDは変わりません。 ``s[0] = x`` リスト代入の後、 ``s[0] is x`` が保証されま" "す。" #: ../../faq/programming.rst:1838 msgid "" "3) If an object is a singleton, it means that only one instance of that " "object can exist. After the assignments ``a = None`` and ``b = None``, it " "is guaranteed that ``a is b`` because ``None`` is a singleton." msgstr "" "3) オブジェクトがシングルトンなら、それはそのオブジェクトのインスタンスは1" "つだけ存在できることを意味します。 ``a = None`` と ``b = None`` 代入の後、 " "``a is b`` が保証されます。``None`` がシングルトンのためです。" #: ../../faq/programming.rst:1842 msgid "" "In most other circumstances, identity tests are inadvisable and equality " "tests are preferred. In particular, identity tests should not be used to " "check constants such as :class:`int` and :class:`str` which aren't " "guaranteed to be singletons::" msgstr "" "多くの他の状況では、同一性テストは賢明でなく、等価性テストをお勧めします。 " "特に、シングルトンであることが保証されていない :class:`int` や :class:`str` " "などの定数をチェックするために同一性テストを使わないでください。" #: ../../faq/programming.rst:1859 msgid "Likewise, new instances of mutable containers are never identical::" msgstr "" "同様に、ミュータブルなコンテナの新しいインスタンスは同一ではありません::" #: ../../faq/programming.rst:1866 msgid "" "In the standard library code, you will see several common patterns for " "correctly using identity tests:" msgstr "" "標準ライブラリのコードには、同一性テストを正しく使うための一般的なパターンが" "あります:" #: ../../faq/programming.rst:1869 msgid "" "1) As recommended by :pep:`8`, an identity test is the preferred way to " "check for ``None``. This reads like plain English in code and avoids " "confusion with other objects that may have boolean values that evaluate to " "false." msgstr "" "1) :pep:`8` で推奨されるように、同一性テストは ``None`` のチェックの良い方法" "です。 コードの中で平易な英語のように読めますし、 false と評価される真偽値を" "持ちうる他のオブジェクトとの混同を避けます。" #: ../../faq/programming.rst:1873 msgid "" "2) Detecting optional arguments can be tricky when ``None`` is a valid input " "value. In those situations, you can create a singleton sentinel object " "guaranteed to be distinct from other objects. For example, here is how to " "implement a method that behaves like :meth:`dict.pop`::" msgstr "" "2) ``None`` が有効な入力値である場合、省略された引数を検出にはコツがいりま" "す。 そのような状況では、他のオブジェクトと区別されることが保証されたシング" "ルトンの番兵オブジェクトを作れます。 例えば、これは :meth:`dict.pop` のよう" "に振る舞うメソッドを実装する方法です:" #: ../../faq/programming.rst:1889 msgid "" "3) Container implementations sometimes need to augment equality tests with " "identity tests. This prevents the code from being confused by objects such " "as ``float('NaN')`` that are not equal to themselves." msgstr "" "3) コンテナの実装では、等価性テストを同一性テストで補強しないといけない場合" "があります。 これは、 ``float('NaN')`` のような自分自身と等価でないオブジェ" "クトによってコードが混乱するのを防ぐためです。" #: ../../faq/programming.rst:1893 msgid "" "For example, here is the implementation of :meth:`collections.abc.Sequence." "__contains__`::" msgstr "" #: ../../faq/programming.rst:1904 msgid "" "How can a subclass control what data is stored in an immutable instance?" msgstr "" "どうすればサブクラスはイミュータブルなインスタンスに格納されたデータを制御で" "きますか?" #: ../../faq/programming.rst:1906 msgid "" "When subclassing an immutable type, override the :meth:`~object.__new__` " "method instead of the :meth:`~object.__init__` method. The latter only runs " "*after* an instance is created, which is too late to alter data in an " "immutable instance." msgstr "" "イミュータブル型をサブクラス化する場合、 :meth:`~object.__init__` ではなく :" "meth:`~object.__new__` メソッドを継承します。 前者はインスタンスが生成され" "た *後* に動くため、イミュータブルなインスタンスのデータを変えるには遅すぎま" "す。" #: ../../faq/programming.rst:1911 msgid "" "All of these immutable classes have a different signature than their parent " "class:" msgstr "" "これらのイミュータブルクラスはすべて、親クラスと異なるシグネチャを持ちます:" #: ../../faq/programming.rst:1937 msgid "The classes can be used like this:" msgstr "クラスはこのように使えます:" #: ../../faq/programming.rst:1952 msgid "How do I cache method calls?" msgstr "メソッド呼び出しをキャッシュするには どうしたらいいですか?" #: ../../faq/programming.rst:1954 msgid "" "The two principal tools for caching methods are :func:`functools." "cached_property` and :func:`functools.lru_cache`. The former stores results " "at the instance level and the latter at the class level." msgstr "" "メソッドキャッシュの主な道具は2つあり、 :func:`functools.cached_property` " "と :func:`functools.lru_cache` です。前者はインスタンスレベル、後者はクラスレ" "ベルで結果を保存します。" #: ../../faq/programming.rst:1959 msgid "" "The *cached_property* approach only works with methods that do not take any " "arguments. It does not create a reference to the instance. The cached " "method result will be kept only as long as the instance is alive." msgstr "" "*cached_property* アプローチは、引数を取らないメソッドでのみ働きます。これは" "インスタンスへの参照を作りません。キャッシュされたメソッドの結果は、インスタ" "ンスが生きている間だけ保持されます。" #: ../../faq/programming.rst:1963 msgid "" "The advantage is that when an instance is no longer used, the cached method " "result will be released right away. The disadvantage is that if instances " "accumulate, so too will the accumulated method results. They can grow " "without bound." msgstr "" "利点は、インスタンスが使われなくなった場合、キャッシュされたメソッドの結果が" "すぐに解放されることです。欠点は、インスタンスが溜まると、溜められたメソッド" "の結果も増えてしまうことです。それらは際限なく増える恐れがあります。" #: ../../faq/programming.rst:1968 msgid "" "The *lru_cache* approach works with methods that have hashable arguments. " "It creates a reference to the instance unless special efforts are made to " "pass in weak references." msgstr "" #: ../../faq/programming.rst:1972 msgid "" "The advantage of the least recently used algorithm is that the cache is " "bounded by the specified *maxsize*. The disadvantage is that instances are " "kept alive until they age out of the cache or until the cache is cleared." msgstr "" "least recently used アルゴリズム(訳注:LRU 直近に使われたものを残す)の利点" "は、キャッシュが指定された *maxsize* で制限されることです。欠点は、キャッシュ" "から期限切れで追い出されるかクリアされるまで、インスタンスが生き続けることで" "す。" #: ../../faq/programming.rst:1977 msgid "This example shows the various techniques::" msgstr "この例は各種テクニックを示します::" #: ../../faq/programming.rst:2001 msgid "" "The above example assumes that the *station_id* never changes. If the " "relevant instance attributes are mutable, the *cached_property* approach " "can't be made to work because it cannot detect changes to the attributes." msgstr "" "上の例では、 *station_id* が常に変わらないことを前提としています。関連するイ" "ンスタンスの属性が可変である場合、 *cached_property* アプローチは属性の変更を" "検出できないため、機能しなくなります。" #: ../../faq/programming.rst:2006 msgid "" "The *lru_cache* approach can be made to work, but the class needs to define " "the *__eq__* and *__hash__* methods so the cache can detect relevant " "attribute updates::" msgstr "" #: ../../faq/programming.rst:2032 msgid "Modules" msgstr "モジュール" #: ../../faq/programming.rst:2035 msgid "How do I create a .pyc file?" msgstr ".pyc ファイルを作るにはどうしますか?" #: ../../faq/programming.rst:2037 msgid "" "When a module is imported for the first time (or when the source file has " "changed since the current compiled file was created) a ``.pyc`` file " "containing the compiled code should be created in a ``__pycache__`` " "subdirectory of the directory containing the ``.py`` file. The ``.pyc`` " "file will have a filename that starts with the same name as the ``.py`` " "file, and ends with ``.pyc``, with a middle component that depends on the " "particular ``python`` binary that created it. (See :pep:`3147` for details.)" msgstr "" "モジュールが初めてインポートされたとき (もしくは、現在のコンパイルされたファ" "イルが作られてから、ソースファイルが変更されたとき) 、コンパイルされたコード" "が入っている ``.pyc`` ファイルが、 ``.py`` ファイルのあるディレクトリのサブ" "ディレクトリ ``__pycache__`` に作成されます。 ``.pyc`` ファイルのファイル名" "は、 ``.py`` ファイルの名前で始まり、 ``.pyc`` で終わり、中間部分はこのファイ" "ルを作った ``python`` バイナリに依存した文字列になります。 (詳細は :pep:" "`3147` を参照してください。)" #: ../../faq/programming.rst:2045 msgid "" "One reason that a ``.pyc`` file may not be created is a permissions problem " "with the directory containing the source file, meaning that the " "``__pycache__`` subdirectory cannot be created. This can happen, for " "example, if you develop as one user but run as another, such as if you are " "testing with a web server." msgstr "" "``.pyc`` が作られない理由の 1 つは、ソースファイルがあるディレクトリの権限の" "問題、つまり ``__pycache__`` サブディレクトリが作れない問題です。これは、例え" "ば、ウェブサーバーでテストを行っているときのような、開発者のユーザと実行者の" "ユーザが別な場合に、起こり得ます。" #: ../../faq/programming.rst:2050 msgid "" "Unless the :envvar:`PYTHONDONTWRITEBYTECODE` environment variable is set, " "creation of a .pyc file is automatic if you're importing a module and Python " "has the ability (permissions, free space, etc...) to create a " "``__pycache__`` subdirectory and write the compiled module to that " "subdirectory." msgstr "" ":envvar:`PYTHONDONTWRITEBYTECODE` 環境変数がセットされない限り、モジュールを" "インポートしていて、 Python に ``__pycache__`` サブディレクトリを作り、そこに" "コンパイルされたモジュールが置ける能力 (権限、ディスクの空きスペース、など) " "がある場合は、 .pyc ファイルは自動的に作られます。" #: ../../faq/programming.rst:2055 msgid "" "Running Python on a top level script is not considered an import and no ``." "pyc`` will be created. For example, if you have a top-level module ``foo." "py`` that imports another module ``xyz.py``, when you run ``foo`` (by typing " "``python foo.py`` as a shell command), a ``.pyc`` will be created for " "``xyz`` because ``xyz`` is imported, but no ``.pyc`` file will be created " "for ``foo`` since ``foo.py`` isn't being imported." msgstr "" "最上位のスクリプトを Python で実行するのはインポートとはみなされず、``.pyc`` " "は作成されません。例えば、最上位のモジュール ``foo.py`` が別のモジュール " "``xyz.py`` をインポートしている場合、(シェルコマンドとして ``python foo.py`` " "と打ち込んで) ``foo`` を実行すると、``xyz`` はインポートされるので ``xyz`` " "の ``.pyc`` は作成されますが、``foo.py`` はインポートされたわけではないので " "``foo`` の ``.pyc`` は作られません。" #: ../../faq/programming.rst:2062 msgid "" "If you need to create a ``.pyc`` file for ``foo`` -- that is, to create a ``." "pyc`` file for a module that is not imported -- you can, using the :mod:" "`py_compile` and :mod:`compileall` modules." msgstr "" "``foo`` の ``.pyc`` ファイルを作成する -- つまり、インポートされていないモ" "ジュールの ``.pyc`` ファイルを作成する -- 必要がある場合、 :mod:`py_compile` " "モジュールと :mod:`compileall` モジュールを使えば可能です。" #: ../../faq/programming.rst:2066 msgid "" "The :mod:`py_compile` module can manually compile any module. One way is to " "use the ``compile()`` function in that module interactively::" msgstr "" ":mod:`py_compile` モジュールは手動で任意のモジュールをコンパイルできます。や" "り方の一つは、このモジュールの ``compile()`` 関数をインタラクティブに実行する" "ことです::" #: ../../faq/programming.rst:2072 msgid "" "This will write the ``.pyc`` to a ``__pycache__`` subdirectory in the same " "location as ``foo.py`` (or you can override that with the optional parameter " "``cfile``)." msgstr "" "このように実行すると、``foo.py`` と同じ場所の ``__pycache__`` サブディレクト" "リに ``.pyc`` が書き出されます (出力ファイルの位置は、オプション引数 " "``cfile`` で上書きすることもできます)。" #: ../../faq/programming.rst:2076 msgid "" "You can also automatically compile all files in a directory or directories " "using the :mod:`compileall` module. You can do it from the shell prompt by " "running ``compileall.py`` and providing the path of a directory containing " "Python files to compile::" msgstr "" ":mod:`compileall` モジュールを使えば自動的に一つや複数のディレクトリのすべて" "のファイルをコンパイルできます。シェルプロンプトから ``compileall.py`` を起動" "して、コンパイルしたいファイルを含むディレクトリのパスを指定してください::" #: ../../faq/programming.rst:2085 msgid "How do I find the current module name?" msgstr "現在のモジュール名を知るにはどうしますか?" #: ../../faq/programming.rst:2087 msgid "" "A module can find out its own module name by looking at the predefined " "global variable ``__name__``. If this has the value ``'__main__'``, the " "program is running as a script. Many modules that are usually used by " "importing them also provide a command-line interface or a self-test, and " "only execute this code after checking ``__name__``::" msgstr "" "モジュールは前もって定義されたグローバル変数 ``__name__`` を検索することで自" "身の名前を決定できます。この値が ``'__main__'`` であるとき、そのプログラムは" "スクリプトとして実行されています。インポートされることによって使われる大抵の" "モジュールはコマンドラインインターフェースや自己テストも提供していて、" "``__name__`` をチェックしてからそのコードだけを実行します::" #: ../../faq/programming.rst:2102 msgid "How can I have modules that mutually import each other?" msgstr "相互にインポートしあうモジュールを作るにはどうしたらいいですか?" #: ../../faq/programming.rst:2104 msgid "Suppose you have the following modules:" msgstr "以下のモジュールがあったとしましょう:" #: ../../faq/programming.rst:2106 msgid ":file:`foo.py`::" msgstr ":file:`foo.py`::" #: ../../faq/programming.rst:2111 msgid ":file:`bar.py`::" msgstr ":file:`bar.py`::" #: ../../faq/programming.rst:2116 msgid "The problem is that the interpreter will perform the following steps:" msgstr "問題はインタプリタが以下の段階を実行することです:" #: ../../faq/programming.rst:2118 msgid "main imports ``foo``" msgstr "main が ``foo`` をインポートする" #: ../../faq/programming.rst:2119 msgid "Empty globals for ``foo`` are created" msgstr "``foo`` の空のグローバルが生成される" #: ../../faq/programming.rst:2120 msgid "``foo`` is compiled and starts executing" msgstr "``foo`` がコンパイルされ実行を始める" #: ../../faq/programming.rst:2121 msgid "``foo`` imports ``bar``" msgstr "``foo`` が ``bar`` をインポートする" #: ../../faq/programming.rst:2122 msgid "Empty globals for ``bar`` are created" msgstr "``bar`` の空のグローバルが生成される" #: ../../faq/programming.rst:2123 msgid "``bar`` is compiled and starts executing" msgstr "``bar`` がコンパイルされ実行を始める" #: ../../faq/programming.rst:2124 msgid "" "``bar`` imports ``foo`` (which is a no-op since there already is a module " "named ``foo``)" msgstr "" "``bar`` が ``foo`` をインポートする(すでに ``foo`` という名前のモジュールがあ" "るので no-op となる)" #: ../../faq/programming.rst:2125 msgid "" "The import mechanism tries to read ``foo_var`` from ``foo`` globals, to set " "``bar.foo_var = foo.foo_var``" msgstr "" "インポートメカニズムは ``foo`` のグローバルから ``foo_var`` を読んで、 ``bar." "foo_var = foo.foo_var`` に設定しようとします。" #: ../../faq/programming.rst:2127 msgid "" "The last step fails, because Python isn't done with interpreting ``foo`` yet " "and the global symbol dictionary for ``foo`` is still empty." msgstr "" "この最後の段階は失敗します。Python が ``foo`` を解釈し終わっていなくて、" "``foo`` のグローバルなシンボルの辞書はまだ空ですから。" #: ../../faq/programming.rst:2130 msgid "" "The same thing happens when you use ``import foo``, and then try to access " "``foo.foo_var`` in global code." msgstr "" "``import foo`` を使って、グローバルコードの ``foo.foo_var`` にアクセスしよう" "としたときにも、これと同じことが起こります。" #: ../../faq/programming.rst:2133 msgid "There are (at least) three possible workarounds for this problem." msgstr "この問題には (少なくとも) 三つの解決策があります。" #: ../../faq/programming.rst:2135 msgid "" "Guido van Rossum recommends avoiding all uses of ``from import ..." "``, and placing all code inside functions. Initializations of global " "variables and class variables should use constants or built-in functions " "only. This means everything from an imported module is referenced as " "``.``." msgstr "" "Guido van Rossum は ``from import ...`` を全く使わないで、すべての" "コードを関数の中に入れることを勧めています。グローバル変数とクラス変数の初期" "化は定数とビルトイン関数のみで行われるべきです。これでインポートされたすべて" "のモジュールは ``.`` として参照されることになります。" #: ../../faq/programming.rst:2140 msgid "" "Jim Roskind suggests performing steps in the following order in each module:" msgstr "" "Jim Roskind はそれぞれのモジュールに対して以下の順に進めることを提案していま" "す:" #: ../../faq/programming.rst:2142 msgid "" "exports (globals, functions, and classes that don't need imported base " "classes)" msgstr "" "エクスポート (インポートされた基底クラスを必要としないグローバル、関数、クラ" "ス)" #: ../../faq/programming.rst:2144 msgid "``import`` statements" msgstr "``import`` 文" #: ../../faq/programming.rst:2145 msgid "" "active code (including globals that are initialized from imported values)." msgstr "" "アクティブなコード (インポートされた値によって初期化されるグローバルを含む)。" #: ../../faq/programming.rst:2147 msgid "" "Van Rossum doesn't like this approach much because the imports appear in a " "strange place, but it does work." msgstr "" "インポートが奇妙な場所に現れることから Van Rossum はこの方法をそれほど好みま" "せんが、これは有効です。" #: ../../faq/programming.rst:2150 msgid "" "Matthias Urlichs recommends restructuring your code so that the recursive " "import is not necessary in the first place." msgstr "" "Matthias Urlichs は第一に再帰インポートが必要ないようにコードを構築しなおすこ" "とを推奨しています。" #: ../../faq/programming.rst:2153 msgid "These solutions are not mutually exclusive." msgstr "これらの解決策はそれぞれ両立させることもできます。" #: ../../faq/programming.rst:2157 msgid "__import__('x.y.z') returns ; how do I get z?" msgstr "" "__import__('x.y.z') は を返しますが、z を得るためにはどうします" "か?" #: ../../faq/programming.rst:2159 msgid "" "Consider using the convenience function :func:`~importlib.import_module` " "from :mod:`importlib` instead::" msgstr "" ":mod:`importlib` に :func:`~importlib.import_module` という便利な関数があるの" "で、代わりにそちらを使用することを検討してください。" #: ../../faq/programming.rst:2166 msgid "" "When I edit an imported module and reimport it, the changes don't show up. " "Why does this happen?" msgstr "" "インポートされたモジュールを編集してから再インポートしましたが、変化が現れま" "せん。なぜですか?" #: ../../faq/programming.rst:2168 msgid "" "For reasons of efficiency as well as consistency, Python only reads the " "module file on the first time a module is imported. If it didn't, in a " "program consisting of many modules where each one imports the same basic " "module, the basic module would be parsed and re-parsed many times. To force " "re-reading of a changed module, do this::" msgstr "" "効率と一貫性上の理由から、Python はモジュールが最初にインポートされた時にのみ" "モジュールファイルを読み込みます。そうしないと、たくさんのモジュールでできて" "いて、それぞれが同じ基本モジュールをインポートしているようなプログラムでは、" "その基本モジュールの解析と再解析が繰り返されることになります。変更されさたモ" "ジュールの再読込を強制するには、こうしてください::" #: ../../faq/programming.rst:2178 msgid "" "Warning: this technique is not 100% fool-proof. In particular, modules " "containing statements like ::" msgstr "注意:この手法は 100%安全とは言えません。とりわけ ::" #: ../../faq/programming.rst:2183 msgid "" "will continue to work with the old version of the imported objects. If the " "module contains class definitions, existing class instances will *not* be " "updated to use the new class definition. This can result in the following " "paradoxical behaviour::" msgstr "" "のような文を含むモジュールは、インポートされたオブジェクトの古いバージョンを" "使い続けます。そのモジュールにクラス定義が含まれていたら、存在するクラスイン" "スタンスは新しいクラス定義を使うようにアップデート *されません*。これによって" "以下の矛盾した振舞いがなされえます::" #: ../../faq/programming.rst:2196 msgid "" "The nature of the problem is made clear if you print out the \"identity\" of " "the class objects::" msgstr "" "この問題の本質は、クラスオブジェクトの \"固有値\" を印字することで明らかにな" "ります::"