Python.use(better) #真理値表: step03 -- def __repr__(self):
‖記事一覧‖ Python.use(better)《Python3.1》
def __repr__(self):
《著》森こねこ、小粒ちゃん+∞《監修》小泉ひよ子とタマゴ倶楽部
第0版♪2001/03/02 ● 第1版♪2003/05/25 ● 第2版♪2004/06/01 ● 第3版♪2009/02/28
課題を作成する過程を通して「論理演算/文字列処理」の理解を深めます。
※ Python1.5 で作成した例題を、Python3.1 で再構成しました。
事例:コードの解説
class TruthTable(object):
...
def _table(self):
B = True,False
return [b1 and b2
for b1 in B for b2 in B]
def __repr__(self):
s = self._body()
return "".join(s)
def _body(self):
B = "TF"
s = []
for i,e in enumerate(self):
c = "%s %s | %s\n"%(B[i//2], B[i%2], e)
s.append(c)
return s
■ #1: 内包を使って
## ---------------------------------------- before def _table(self): s = [] B = True, False for b1 in B: for b2 in B: b = b1 and b2 s.append(b) return s ## ---------------------------------------- after def _table(self): B = True,False return [b1 and b2 for b1 in B for b2 in B]
for 文と同等のものは「内包」を使うと、より簡潔に記述できます。
■ #2: メソッド:__repr__
def __repr__(self):
s = self._body()
return "".join(s)
def _body(self):
B = "TF"
s = []
for i,e in enumerate(self):
c = "%s %s | %s\n"%(B[i//2], B[i%2], e)
s.append(c)
return s
メソッド _body は(__repr__ の補助関数として)オブジェクトに固有の文字列表現を規定します。
- 組み込み関数 enumerate を利用すると、インスタンス属性が保持する各文字 e(長さ1の文字列)と、先頭からのオフセット値 i が得られます。
- 式 B[i//2] は左項の、式 B[i%2] は右項の、真理値を表わす文字を参照します。
事例:モジュールを起動する
■ 全項目を確認する
全ステップの「項目」を確認するには、関数 do を利用します。
$ python -i TruthTable.py >>> do() 0: step00 -- class TruthTable(object): 1: step01 -- def __init__(self): 2: step02 -- def __iter__(self): 3: step03 -- def __repr__(self): 4: step04 -- def _body(self): 5: step05 -- def op_and(self): 6: step06 -- def operator(self, op): 7: step07 -- def implication(self): >>>