Last active
April 2, 2016 05:05
-
-
Save Cartman0/8eb511c3b2aa6cadad6f6d49666c9db2 to your computer and use it in GitHub Desktop.
Dive Into Python3 7章メモ(クラスとイテレータ)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"cells": [ | |
{ | |
"metadata": { | |
"toc": "true" | |
}, | |
"cell_type": "markdown", | |
"source": "# Table of Contents\n <p><div class=\"lev1\"><a href=\"#7章-クラスとイテレータ-1\"><span class=\"toc-item-num\">1 </span>7章 クラスとイテレータ</a></div><div class=\"lev2\"><a href=\"#飛び込む-1.1\"><span class=\"toc-item-num\">1.1 </span>飛び込む</a></div><div class=\"lev2\"><a href=\"#クラスを定義する-1.2\"><span class=\"toc-item-num\">1.2 </span>クラスを定義する</a></div><div class=\"lev3\"><a href=\"#init()メソッド-1.2.1\"><span class=\"toc-item-num\">1.2.1 </span><strong>init</strong>()メソッド</a></div><div class=\"lev2\"><a href=\"#クラスをインスタンス化する-1.3\"><span class=\"toc-item-num\">1.3 </span>クラスをインスタンス化する</a></div><div class=\"lev2\"><a href=\"#インスタンス変数-1.4\"><span class=\"toc-item-num\">1.4 </span>インスタンス変数</a></div><div class=\"lev2\"><a href=\"#フィボナッチイテレータ-1.5\"><span class=\"toc-item-num\">1.5 </span>フィボナッチイテレータ</a></div><div class=\"lev2\"><a href=\"#名詞を複数形にする規則のイテレータ-1.6\"><span class=\"toc-item-num\">1.6 </span>名詞を複数形にする規則のイテレータ</a></div><div class=\"lev2\"><a href=\"#インスタンス変数のスコープについて-1.7\"><span class=\"toc-item-num\">1.7 </span>インスタンス変数のスコープについて</a></div><div class=\"lev2\"><a href=\"#参考リンク-1.8\"><span class=\"toc-item-num\">1.8 </span>参考リンク</a></div>" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "- [Dive Into Python3 1章メモ](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/d54093a99b9254c81bf1123adacbc48a/raw/eedc90bbbfc14e259854f2e739fffeec4cb4d8f7/DiveIntoPython3_01.ipynb)\n- [Dive Into Python3 2章メモ(ネイティブデータ型)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/988b51d8482ad9ade835bb07efdffb38/raw/784cf276b7cebe254e59f09dcea6f09eea760d38/DiveIntoPython3_02.ipynb)\n- [Dive Into Python3 3章メモ(内包表記)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/183ec6f6c835f621106f7c27d215290a/raw/bd7677946d6400bbe6acd257df7fb9c5976c3320/DiveIntoPython3_03.ipynb)\n- [Dive Into Python3 4章メモ(文字列)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/bb974f82e8a3fc74ac82c3c2a5b1a4f9/raw/63a80011c9391b451108c1a4dc804ec5ff125f34/DiveIntoPython3_04.ipynb)\n- [Dive Into Python3 5章メモ(正規表現)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/b834807a0dabb1c458b87be2f333a5ca/raw/37d6f25f67e017a569e1f0b60a9fcbe49d50515f/DiveIntoPython3_05.ipynb?flush_cache=true)\n- [Dive Into Python3 6章メモ(クロージャとジェネレータ)](http://nbviewer.jupyter.org/urls/gist.githubusercontent.com/Cartman0/a8998f8f88c5578271495ada56cc4809/raw/4e9b8ef3543016a710f905215693694acd703549/DiveIntoPython3_06.ipynb?flush_cache=true)" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "# 7章 クラスとイテレータ" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "## 飛び込む" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "イテレーターはどんなところにもいて、あらゆるものの礎をなしているが、その姿はいつも目に見えない。\n内包表記はイテレータの単純形に過ぎないし、\nジェネレータもイテレータの単純形に過ぎない。\n値を`yield`する関数というのは、イテレータを組み立てることなしにイテレータを作るコンパクトで上手い方法。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "## クラスを定義する" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "Pythonは完全にオブジェクト指向の言語なので、\n独自のクラスを定義したり、自作のクラスや組み込みのクラスを継承したり、自分で定義したクラスをインスタンス化したりできる。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "Pythonではクラスを簡単に定義できる。\n関数でもそうだったように、クラスを定義する場所が他と区別されているなどということはない。\n\nPythonのクラス定義は、`class` という予約語から始まり、\nその後ろにクラス名を書く。\n形の上で言えば、クラスは別に他のクラスを継承しなくてもよいので、定義するのに最低限必要なものはこれだけ。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "このクラスの名前は「PapayaWhip」であり、\nこのクラスは他のクラスを継承していない。\nクラス名は、EachWordLikeThisのように「各単語の先頭を大文字にするのが普通」。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": true, | |
"code_folding": [], | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "class PapayaWhip:\n pass ", | |
"execution_count": 1, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "pass文は、JavaやC言語における空っぽの波括弧({})のようなもの。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "名前を除けば、Pythonのクラスが絶対に持っていなければならないものなど無い。\n\n必須ではないが、Pythonのクラスはコンストラクタに似た`__init__()`メソッドを持つことができる。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "### __init__()メソッド" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "次のコードでは `__init__`メソッドを使ってFibクラスを初期化している。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "モジュールや関数と同様に、クラスもdocstringを持つことができる." | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "`__init__()`メソッドは、\nクラスのインスタンスが生成されるとすぐに呼び出される。\n\nこのメソッドのことをクラスの「コンストラクタ」と呼びたくなるかもしれないが、それは厳密には誤り。\n確かに、これはC++のコンストラクタと似たものに見えるし(慣例上、`__init__()`メソッドはクラスの一番初めに定義される)、\n同じような処理をするし(新しく作成されたインスタンスのなかで一番最初に実行される)、名前自体もそれっぽい。\nしかし、そう呼ぶのは正しくない。\n\n`__init__()`メソッドが呼び出されたときにはオブジェクトはすでに作成されている。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "class Fib:\n '''iterator that yields numbers in the Fibonacci sequence'''\n \n def __init__(self, max):\n pass\n \n", | |
"execution_count": 2, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "`__init__()`メソッドを含むすべてのメソッドの最初の引数は、\n現在のインスタンスへの参照だ。\n慣例により、この引数には`self` という名前を付ける。\nこの引数は、c++やJavaにおける予約語`this` と同じ役割を果たすが、\n`self` はPythonの予約語ではなく、単に慣例上そう名付けられているだけでしかない。\n**self以外の名前を付けない**。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "`__init__()`メソッドの中では、`self` は新しく作成されたオブジェクトを指している。\nそれ以外のメソッドでは、`self` はメソッドが呼び出されたインスタンスを参照している。メソッドを定義するときは`self`引数を明示的に書く必要があるのだが、\nメソッドを呼び出すときにはこの引数を与えてはならない。\nPython が自動的に付け加えてくれる。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "## クラスをインスタンス化する" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "Python ではクラスを簡単にインスタンス化できる。\nクラスをインスタンス化するには、`__init__()` が要求する引数を渡して、\nクラスを関数のように呼び出すだけで良い。\nすると、戻り値として新しく生成されたオブジェクトが返される。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": true, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "class Fib:\n '''iterator that yields numbers in the Fibonacci sequence'''\n\n def __init__(self, max):\n self.max = max\n\n def __iter__(self):\n self.a = 0\n self.b = 1\n return self\n\n def __next__(self):\n fib = self.a\n if fib > self.max:\n raise StopIteration\n \n (self.a, self.b) = (self.b, self.a + self.b)\n return fib\n \n", | |
"execution_count": 3, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "Fibクラスの新しいインスタンスを作り、それを変数fibに代入している。\n100という引数を1つ渡しているが、これは結局Fibクラスの `__init__()`メソッドで`max`引数として扱われる。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": true, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "fib = Fib(100)", | |
"execution_count": 4, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "fibはFibクラスのインスタンスになった。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "fib", | |
"execution_count": 5, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "<__main__.Fib at 0x213d04b96a0>" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 5 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "どんなクラスのインスタンスも組み込み属性の`__class__` を持っているが、\nこの属性はそのオブジェクトのクラスを指している。\n\nJavaのプログラマなら、getName()やgetSuperclass()といったオブジェクトのメタデータ情報を得るためのメソッドが入ったClassクラスに馴染みがあるかもしれない。\nPythonでは属性を通じてこの種のメタデータに参照することになるのだが、その考え方自体は同じ。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "fib.__class__", | |
"execution_count": 6, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "__main__.Fib" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 6 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "インスタンスのdocstring には、関数やモジュールの場合と同じやり方でアクセスできる。ある1つのクラスのインスタンスはすべて同じdocstring を持つ。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "fib.__doc__", | |
"execution_count": 7, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "'iterator that yields numbers in the Fibonacci sequence'" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 7 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "Pythonでは関数のようにクラスを呼び出すことでクラスの新しいインスタンスを作成できる。\nc++やJavaにあるような明示的なnew演算子は存在しない。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "## インスタンス変数" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "`self.max` というのは、インスタンス変数。\n`__init__()`メソッドに引数として渡された`max` とは違う。\n`self.max` は、このインスタンスにおいて「グローバル」だ。要するに、他のメソッドからこの変数にアクセスできる。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "```\nclass Fib:\n def __init__(self, max):\n self.max = max\n \n```" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "インスタンス変数は、クラスの個々のインスタンスに固有だ。\n例えば、2つの Fibインスタンスを異なる最大値を与えて作った場合、この2つはそれぞれの値を保持することになる。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "fib1 = Fib(100)\nfib2 = Fib(200)\nfib1.max", | |
"execution_count": 8, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "100" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 8 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "fib2.max", | |
"execution_count": 9, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "200" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 9 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "## フィボナッチイテレータ" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "イテレータとは `__iter__()`メソッドを実装した単なるクラスだ。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "`__init__, __iter__, __next__` の3つのメソッドのどれにも、先頭と末尾に2つのアンダースコア(`_`)が付いている。\n通常はこれらが特殊メソッドであることを示している。\n特殊メソッドはクラスやそのインスタンスについて何か他の構文を使ったときに、Pythonがこれらを呼び出す。\n\n特殊メソッドの詳細についてはこちら。\nhttp://diveintopython3-ja.rdy.jp/special-method-names.html" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "イテレータをゼロから作るには、fibを関数ではなくクラスにする必要がある。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "**`__iter__()`メソッドは、\n誰かがiter(fib)を呼び出した時に呼び出される\n(もうすぐ分かるように、forループが自動でこれを呼び出すし、自分の手で呼び出すこともできる)。**\n\nイテレーションを始めるための初期化\n(この例では、2つのカウンタ`self.a` と`self.b` をリセットをする)を終えたら、`__iter__()`メソッドは`__next__()`メソッドを実装した何らかのオブジェクトを返せばよい。\nこの例では(そして多くの場合では)、\nクラス自身が`__next__()`メソッドを実装しているので、\n`__iter__()`はただ単に`self` を返している。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "`__next__()`メソッドが`StopIteration`例外を送出すると、\nこの例外は呼び出し側にイテレーションの終了を告げることになる。\nほとんどの例外とは違って、この例外はエラーではない。\n\nこの例外は正常な状況で送出されるもので、\n単に「イテレータは生成すべき値をこれ以上持っていない」ということを意味するにすぎない。\n仮に呼び出し側がforループだとすると、forループはStopIteration例外に気づいて、何事もなかったかのようにループから脱出する。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "イテレータの `__next__()`メソッドは値を単純にreturnすることで、新しい値を吐き出す。\n\nここでyieldを使ってはならない。ジェネレータにしか使うことができないものだから。\nここではイテレータをゼロから作っているので、代わりにreturnを使う。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": true, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "class Fib:\n def __init__(self, max):\n self.max = max\n \n def __iter__(self):\n self.a = 0\n self.b = 1\n return self\n\n def __next__(self):\n fib = self.a\n if fib > self.max:\n raise StopIteration\n \n (self.a, self.b) = (self.b, self.a + self.b)\n return fib\n \n", | |
"execution_count": 10, | |
"outputs": [] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "for n in Fib(1000):\n print(n, end=' ')\n", | |
"execution_count": 11, | |
"outputs": [ | |
{ | |
"text": "0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 ", | |
"name": "stdout", | |
"output_type": "stream" | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "forループの中では、次のようなことが起きている:\n\nforループは `Fib(1000)` を呼び出している。\nこの呼び出しによってFibクラスのインスタンスが返される。\n\nforループは `iter` を水面下で呼び出してくれる。\nこの呼び出しでイテレータオブジェクトが返される。\nこの例では、`__iter__()`メソッドは `self` を返す.\n\nイテレータの「全体をループする」ために、forループは `next(fib_iter)` を呼び出す。\nこれによってfib_iterオブジェクトの `__next__()` メソッドが呼び出され、このメソッドは次のフィボナッチ数を計算してその値を返す。\nforループはこの値を受け取ってnへ代入し、このnの値についてforループの本文を実行する。\n\nforループは停止すべき時は、 `next` が `StopIteration`例外を送出すると、forループはその例外を飲み込んで、何事もなかったかのようにループを抜ける(その他の例外は飲み込まれること無く、通常通り送出される)。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "## 名詞を複数形にする規則のイテレータ" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "名詞を複数形にする規則のジェネレータをイテレータとして書き換える。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "`LazyRules`クラスをインスタンス化する際に、\nパターンファイルが開かれるが、その中身は一切読み込まない(読み込みは後で行う)。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "パターンファイルを開いたら、キャッシュの初期化を行う。このキャッシュは、あとで(`__next__()`メソッドで)パターンファイルの各行を読み込むときに使う。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": true, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "class LazyRules:\n rules_filename = 'plural6-rules.txt'\n\n def __init__(self):\n self.pattern_file = open(self.rules_filename, encoding='utf-8')\n self.cache = []\n \n", | |
"execution_count": 12, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "`rules_filename` は`__iter__()`メソッドの内部では定義されていない。\nそれどころか、これはどのメソッドの内部でも定義されていない。\nこれはクラスレベルで定義されているのだ。\nこれは**クラス変数** というもので、\nこれにはインスタンス変数とまったく同じやり方(self.rules_filename)でアクセスできるのだが、この変数は `LazyRules`クラスのすべてのインスタンスによって共有されている。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": true, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "class LazyRules:\n rules_filename = 'plural6-rules.txt'\n\n def __init__(self):\n self.pattern_file = open(self.rules_filename, encoding='utf-8')\n self.cache = []\n\n def __iter__(self):\n self.cache_index = 0\n return self\n\n def __next__(self):\n self.cache_index += 1\n if len(self.cache) >= self.cache_index:\n return self.cache[self.cache_index - 1]\n\n if self.pattern_file.closed:\n raise StopIteration\n\n line = self.pattern_file.readline()\n if not line:\n self.pattern_file.close()\n raise StopIteration\n\n pattern, search, replace = line.split(None, 3)\n funcs = build_match_and_apply_functions(pattern, search, replace)\n self.cache.append(funcs)\n return funcs\n \n", | |
"execution_count": 13, | |
"outputs": [] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "r1 = LazyRules()\nr2 = LazyRules()", | |
"execution_count": 14, | |
"outputs": [] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "このクラスの各々のインスタンスは、\nクラスで定義された値を持つ属性 `rules_filename` を受け継いでいる。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true, | |
"scrolled": true | |
}, | |
"cell_type": "code", | |
"source": "r1.rules_filename", | |
"execution_count": 15, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "'plural6-rules.txt'" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 15 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "r2.rules_filename", | |
"execution_count": 16, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "'plural6-rules.txt'" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 16 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "1つのインスタンスの属性値を変更しても、他のインスタンスの属性値には影響を与えない。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "r2.rules_filename = 'r2-override.txt'\nr2.rules_filename", | |
"execution_count": 17, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "'r2-override.txt'" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 17 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "r1.rules_filename", | |
"execution_count": 18, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "'plural6-rules.txt'" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 18 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "クラス属性も変更しない。\nクラス自体にアクセスするための特殊属性`__class__`を使うことで、\n(個々のインスタンスの属性ではなく)クラス属性を参照できる。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true, | |
"scrolled": true | |
}, | |
"cell_type": "code", | |
"source": "r2.__class__.rules_filename", | |
"execution_count": 19, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "'plural6-rules.txt'" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 19 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "r1.__class__.rules_filename", | |
"execution_count": 20, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "'plural6-rules.txt'" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 20 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "クラス属性を変更すると、\nまだ値を受け継いでいるインスタンス(ここではr1)はその影響を受ける。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": true, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "r2.__class__.rules_filename = 'papayawhip.txt' ", | |
"execution_count": 21, | |
"outputs": [] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "r2.__class__.rules_filename", | |
"execution_count": 22, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "'papayawhip.txt'" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 22 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "r1.__class__.rules_filename", | |
"execution_count": 23, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "'papayawhip.txt'" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 23 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "r1.rules_filename", | |
"execution_count": 24, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "'papayawhip.txt'" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 24 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "その属性を上書きしているインスタンス(ここではr2)は影響を受けない。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true, | |
"scrolled": true | |
}, | |
"cell_type": "code", | |
"source": "r2.rules_filename", | |
"execution_count": 25, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "'r2-override.txt'" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 25 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "```\ndef __iter__(self): ①\n self.cache_index = 0\n return self ②\n```\n\n- `__iter__()` メソッドは、\n誰かが(例えばforループが)iter(rules)を呼び出すたびに呼び出される。\n- すべての`__iter__()`メソッドが絶対にやらなればならないのは、イテレータを返すことだけだ。\nこの例の`__iter__()`メソッドは`self` を返している。\nこれは、イテレーション時に値を返す仕事をする`__next__()`メソッドをこのクラスが定義していることを示している。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "```\ndef __next__(self): ①\n .\n .\n .\n pattern, search, replace = line.split(None, 3)\n funcs = build_match_and_apply_functions( ②\n pattern, search, replace)\n self.cache.append(funcs) ③\n return funcs\n```\n\n1. `__next__()` メソッドは、誰か(例えばforループ)がnext(rules)を呼び出すたびに呼び出される。\n2. `build_match_and_apply_functions()`関数は変更されていない。\n3. 唯一の違いは、マッチと処理を行う関数 (タプル funcs に格納されている) を返す前に、それを「self.cacheに保存」している。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "```\ndef __next__(self):\n .\n .\n .\n line = self.pattern_file.readline() ①\n if not line: ②\n self.pattern_file.close()\n raise StopIteration ③\n```\n\n1. `readline()`メソッド(注: 単数形のreadline()で、複数形のreadlines()ではない)は、開かれたファイルからちょうど1行だけを読み込む。具体的には次の1行を読みこむ。\n2. `readline()` が読み込む行がまだある場合には、lineは空の文字列にはならない。たとえファイルが空行を含んでいたとしても、line は1文字の'\\n'(改行文字)という文字列になるだろう。もしlineが本当に空の文字列だったとしたら、\nそれはファイルにもう読み込める行が無い。\n3. ファイルの末尾に到達したら、そのファイルを閉じて魔法のStopIteration例外を発生させなければならない。\nこの行までたどり着いた理由は、「新しい規則に基づいてマッチと処理を行う関数」を必要としていたからだということを思いだそう。\n新しい規則はファイルの次の行から得られるわけだが、その次の行とやらは存在しない.\nつまり、返す値がもう無いので、イテレーションは終わり。" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "```\ndef __next__(self):\n self.cache_index += 1\n if len(self.cache) >= self.cache_index:\n return self.cache[self.cache_index - 1] ①\n\n if self.pattern_file.closed:\n raise StopIteration ②\n```\n\n1. `self.cache` は、それぞれの規則に基づいてマッチと処理を行うために必要な関数のリストになるもの。\n`self.cache_index` は、キャッシュされた要素のうち、次にどれを返さなければならないかを記録している。キャッシュがまだ残っている場合には\n(つまりself.cacheの長さが`self.cache_index` よりも大きい場合は)キャッシュが使える。\nマッチと処理を行う関数を初めから作るかわりに、値をキャッシュから取り出して返すことができる。\n\n2. その一方で、キャッシュにヒットせず、なおかつファイルオブジェクトが既に閉じられている場合は(これが起こる場合については、先ほどこのメソッドの下の方のコードを説明した時に見た)、もうこれ以上やるべきことはない。ファイルが閉じてしまっているということは、このファイルを全部使い切ってしまったということ \n— つまり、既にパターンファイル全体を読み込んでいて、すべてのパターンに基づくマッチと処理の関数を作成し終わり、そのキャッシュ化も済んでいる." | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "まとめ:\n\n1. モジュールがインポートされると、\n`LazyRules` クラスのインスタンスが1つだけ生成され、rulesという名前が付けられる。\nこれはパターンファイルを開くが、その内容は読み込まない。\n\n2. 最初のマッチと処理の関数が要求されると、まずキャッシュが確認されるが、キャッシュが空であることが分かる。\nすると、パターンファイルから1つの行が読み込まれ、そのパターンを元にマッチと処理の関数が作成され、キャッシュされる。\n\n3. 仮に、一番最初の規則がマッチしたとしよう。その場合は、マッチと処理の関数はそれ以上作成されず、パターンファイルからそれ以上は読み込まれない。\n\n4. さらに、今度は別の単語を複数形にするために、呼び出し元が再びplural()関数を呼び出したと仮定しよう。plural()関数のforループはiter(rules)を呼び出し、ここでキャッシュのインデックスは初期化されるが、ファイルオブジェクトはリセットされない。\n\n5. 最初のループで、forループは値をrulesから取得しようとする。\nその結果、`__next__()`メソッドが呼び出されることになるが、\n今回はパターンファイルの1行目に対応するマッチと処理の関数のペアがキャッシュに1つ準備されている。この2つの関数は前の単語を複数形にする時に作成・キャッシュされたものなので、ここでキャッシュから取り出される。そして、キャッシュのインデックスはインクリメントされ、開いたファイルについては触れることもない。\n\n6. 仮に、今回は最初の規則にマッチしなかったとする。\nすると、for文は再びループして、rulesから別の値が取り出そうとする。\nここで`__next__()`メソッドが2度目の呼び出しを受けることになるが、この時点でキャッシュは使い切られている \n— 2つ目のルールが欲しいのに、キャッシュには要素が1つしかない — ので`__next__()`メソッドは処理を続け、開いたファイルから別の行を読み込み、パターンを元にマッチと処理の関数を構築し、この2つの関数をキャッシュする。\n\n7. この読み込み-構築-キャッシュのプロセスは、複数形にしたい単語にパターンファイルから読み込まれた規則がマッチするまで続く。\nもし、ファイルの末尾に達する前にマッチする規則を見つけた場合は、その規則を使って変換を施し処理を停止する。\nこの時、ファイルは開かれたままなので、ファイルポインタは読み込みをやめたところに留まり、次のreadline()の呼び出しを待つ。\n他方で、この処理の間にキャッシュには要素が溜まっていく。次に新しい単語を複数形にしようとした時には、パターンファイルの次の行を読み込む前にキャッシュの中にあるものが試されるのだ。\n\n" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "名詞を複数形にするパラダイスに到達した。\n\n- 最小の起動コスト。import時に行われることは、1つのクラスをインスタンス化するのと、ファイルを開く(しかし内容は読み込まない)ことだけだ。\n\n- 最大限のパフォーマンス。 前のバージョンでは単語を複数形にするたびに、ファイルを読み込んで関数を動的に作成していた。このバージョンでは、関数は作成されるとすぐにキャッシュされる。だから、いくつの単語を複数形にするのであれ、最悪の場合でもパターンファイルは1度だけしか読み込まれない。\n\n- コードとデータの分離。 すべてのパターンは別のファイルに格納されている。コードはコード、データはデータ、二つは決して交わらない。" | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "import re\n\nclass LazyRules:\n '''\n '''\n \n rules_filename = 'plural6-rules.txt'\n\n def __init__(self):\n self.pattern_file = open(self.rules_filename, encoding='utf-8')\n self.cache = []\n\n def __iter__(self):\n self.cache_index = 0\n return self\n\n def __next__(self):\n self.cache_index += 1\n if len(self.cache) >= self.cache_index:\n return self.cache[self.cache_index - 1]\n\n if self.pattern_file.closed:\n raise StopIteration\n\n line = self.pattern_file.readline()\n if not line:\n self.pattern_file.close()\n raise StopIteration\n\n pattern, search, replace = line.split(None, 3)\n funcs = self.__build_match_and_apply_functions(pattern, search, replace)\n self.cache.append(funcs)\n return funcs\n \n def __build_match_and_apply_functions(self, pattern, search, replace):\n def matches_rule(word):\n return re.search(pattern, word)\n def apply_rule(word):\n return re.sub(search, replace, word)\n \n return (matches_rule, apply_rule)\n \n\n\nrules = LazyRules()\n\ndef plural(noun):\n for matches_rule, apply_rule in rules:\n if matches_rule(noun):\n return apply_rule(noun)\n raise ValueError('no matching rule for {0}'.format(noun))\n", | |
"execution_count": 26, | |
"outputs": [] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "rules.cache", | |
"execution_count": 27, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "[]" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 27 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "plural('box')", | |
"execution_count": 28, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "'boxes'" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 28 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "rules.cache", | |
"execution_count": 29, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "[(<function __main__.LazyRules.__build_match_and_apply_functions.<locals>.matches_rule>,\n <function __main__.LazyRules.__build_match_and_apply_functions.<locals>.apply_rule>)]" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 29 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true, | |
"scrolled": true | |
}, | |
"cell_type": "code", | |
"source": "plural('vancy')", | |
"execution_count": 30, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "'vancies'" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 30 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "rules.cache", | |
"execution_count": 31, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "[(<function __main__.LazyRules.__build_match_and_apply_functions.<locals>.matches_rule>,\n <function __main__.LazyRules.__build_match_and_apply_functions.<locals>.apply_rule>),\n (<function __main__.LazyRules.__build_match_and_apply_functions.<locals>.matches_rule>,\n <function __main__.LazyRules.__build_match_and_apply_functions.<locals>.apply_rule>),\n (<function __main__.LazyRules.__build_match_and_apply_functions.<locals>.matches_rule>,\n <function __main__.LazyRules.__build_match_and_apply_functions.<locals>.apply_rule>)]" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 31 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "## インスタンス変数のスコープについて" | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "class Cl:\n def __init__(self, v):\n # アンダーバー2つ__ でprivate変数になる。 \n self.__v = v\n \n def get(self):\n return self.__v\n\n\nc = Cl(10)\nc", | |
"execution_count": 32, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "<__main__.Cl at 0x213d04d5588>" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 32 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "c.__v", | |
"execution_count": 33, | |
"outputs": [ | |
{ | |
"evalue": "'Cl' object has no attribute '__v'", | |
"output_type": "error", | |
"traceback": [ | |
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", | |
"\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)", | |
"\u001b[1;32m<ipython-input-33-6d638b89ef51>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mc\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__v\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", | |
"\u001b[1;31mAttributeError\u001b[0m: 'Cl' object has no attribute '__v'" | |
], | |
"ename": "AttributeError" | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true, | |
"scrolled": true | |
}, | |
"cell_type": "code", | |
"source": "c.get()", | |
"execution_count": 34, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "10" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 34 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "c._Cl__v", | |
"execution_count": 35, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "10" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 35 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "c._Cl__v = 100\nc._Cl__v", | |
"execution_count": 36, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "100" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 36 | |
} | |
] | |
}, | |
{ | |
"metadata": { | |
"collapsed": false, | |
"trusted": true | |
}, | |
"cell_type": "code", | |
"source": "c.get()", | |
"execution_count": 37, | |
"outputs": [ | |
{ | |
"data": { | |
"text/plain": "100" | |
}, | |
"output_type": "execute_result", | |
"metadata": {}, | |
"execution_count": 37 | |
} | |
] | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "## 参考リンク" | |
}, | |
{ | |
"metadata": {}, | |
"cell_type": "markdown", | |
"source": "- [Dive Into Python3 7章クラスとイテレータ](http://diveintopython3-ja.rdy.jp/iterators.html)\n- [クラス python doc](http://docs.python.jp/3/tutorial/classes.html)" | |
} | |
], | |
"metadata": { | |
"language_info": { | |
"pygments_lexer": "ipython3", | |
"version": "3.5.1", | |
"file_extension": ".py", | |
"codemirror_mode": { | |
"version": 3, | |
"name": "ipython" | |
}, | |
"nbconvert_exporter": "python", | |
"mimetype": "text/x-python", | |
"name": "python" | |
}, | |
"kernelspec": { | |
"name": "python3", | |
"display_name": "Python 3", | |
"language": "python" | |
}, | |
"toc": { | |
"toc_number_sections": true, | |
"toc_cell": true, | |
"toc_window_display": false, | |
"toc_threshold": "6" | |
}, | |
"gist": { | |
"id": "8eb511c3b2aa6cadad6f6d49666c9db2", | |
"data": { | |
"description": "Dive Into Python3 7章メモ(クラスとイテレータ)", | |
"public": true | |
} | |
}, | |
"_draft": { | |
"nbviewer_url": "https://gist.github.com/8eb511c3b2aa6cadad6f6d49666c9db2" | |
} | |
}, | |
"nbformat": 4, | |
"nbformat_minor": 0 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment