Python.use(better) #Stack: step04 -- def __repr__(self):

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

Stack: step04 -- def __repr__(self):

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

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

■ 全項目を確認する

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

$ python -i stack_class.py
>>> do()
0: step00 -- class Stack(list):
1: step01 -- def push(self, item):
2: step02 -- def pop(self):
3: step03 -- class Stack(object):
4: step04 -- def __repr__(self):
5: step05 -- def push(self, item):
6: step06 -- def pop(self):
>>>
■ 各項目を実行する

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

>>> do(4)
>>> # -------------------------------------------------- step04
>>> s = Stack(); s
[]
>>> s.push("A"), s
AttributeError: 'Stack' object has no attribute 'push'
>>>
  • クラス呼び出し Stack() によって、新たなスタック(インスタンス)s を生成します。
  • 変数名 s を介して、インスタンスオブジェクトを参照すると、空のスタックを確認できます。
  • スタック s にメソッド push を適用すると、例外 AttributeError を生成して、エラーメッセージを出力します。

事例:コードの解説

    class Stack(object):
        def __init__(self):
            self.items = []
        def __repr__(self):         #1:
            return repr(self.items)
■ #1: オブジェクトに固有の文字列表現
        def __repr__(self):         #1:
            return repr(self.items)

メソッド __repr__ は、組み込み関数 repr に呼応して、オブジェクトに固有の文字列表現を規定します。

  • インスタンス属性 self.items が保持する要素を列挙した、文字列表現が得られます。


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


関連記事

Last updated♪2009/10/26