Python.use(better) #ASCII: step04 -- def _body(self):

記事一覧 Python.use(better)《Python3.1》

def _body(self):

《著》森こねこ、小粒ちゃん+∞《監修》小泉ひよ子とタマゴ倶楽部
第0版♪2001/03/02 ● 第1版♪2003/05/25 ● 第2版♪2004/06/01 ● 第3版♪2009/02/28

課題を作成する過程を通して「文字列処理」の理解を深めます。
※ Python1.5 で作成した例題を、Python3.1 で再構成しました。

事例:コードの解説

    class ASCII(object):
        ...
        def __repr__(self):
            s = self._body()
            return "".join(s)

        def _body(self):
            s = []
            for i,e in enumerate(self):
                c = " "
                if not (i+1)%16:
                    c = "\n"
                s.append(e+c)
            return s
■ #1: メソッド:__repr__
        def _body(self):
            s = []
            for i,e in enumerate(self):
                c = " "
                if not (i+1)%16:
                    c = "\n"
                s.append(e+c)
            return s

メソッド _body は(__repr__ の補助関数として)オブジェクトに固有の文字列表現を列挙して、リスト s に収集します。

  • 組み込み関数 enumerate を利用すると、インスタンス属性 self.cset が保持する各文字 e(長さ1の文字列)と、先頭からのオフセット値 i が得られます。
  • 変数 c は、各文字 e を区切る文字(空白文字 " ")を保持します。ただし、16 文字ごとに改行文字 "\n" を設定します。

事例:モジュールを起動する

■ 全項目を確認する

全ステップの「項目」を確認するには、関数 do を利用します。

$ python -i ascii.py
>>> do()
0: step00 -- class ASCII(object):
1: step01 -- def __init__(self):
2: step02 -- def _cset(self):
3: step03 -- [chr(e) for e in ...]
4: step04 -- def _body(self):
5: step05 -- c = " \n"[not (i+1)%16]
6: step06 -- [e+" \n"[not (i+1)%16]
7: step07 -- def _header(self):
8: step08 -- def _title(self):
9: step09 -- def _body(self):
>>>
■ 各項目を実行する

各ステップの「動作」を確認するには、関数 do に実引数を指定します。

>>> do(4)
>>> # -------------------------------------------------- step04
>>> ASCII()
0 1 2 3 4 5 6 7 8 9 : ; < = > ?
@ A B C D E F G H I J K L M N O
P Q R S T U V W X Y Z 
>>>

クラス ASCII のインスタンスが生成されます。

  • "0" から "Z" までの各文字が出力するとともに、16 文字ごとに改行します。

》こちらに移動中です《
TOP


関連記事

Last updated♪2009/11/23