2013年4月10日水曜日

開発環境

『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のVI部(クラスとオブジェクト指向プログラミング)のまとめ演習3.(サブクラスの作成)を解いてみる。

その他参考書籍

3.(サブクラスの作成)

コード(BBEdit)

sample.py

#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-

class MyList(list):
    def __add__(self, y):
        return MyList(list.__add__(self, y))
    def __iadd__(self, y):
        return MyList(list.__iadd__(self, y))
    def __imull__(self, y):
        return MyList(list.__imull__(self, y))
    def __mul__(self, n):
        return MyList(list.__mul__(self, n))
    def __rmull__(self, n):
        return MyList(list.__rmull__(self, n))

class MyListSub(MyList):
    count = 0
    def __init__(self, data):
        print("初期化")
        MyList.__init__(self, data)
        self.count = 0
    def __add__(self, y):
        print("和")
        MyListSub.count += 1
        self.count += 1
        return MyList.__add__(self, y)
    def __iadd__(self, y):
        print("和(複合演算子)")
        MyListSub.count += 1
        self.count += 1
        return MyList.__iadd__(self, y)
    def __imull__(self, n):
        print("積(複合演算子)")
        MyListSub.count += 1
        self.count += 1
        return MyList.__imull__(self, n)
    def __mul__(self, n):
        print("積")
        MyListSub.count += 1
        self.count += 1
        return MyList.__mul__(self, n)
    def __rmull__(self, n):
        print("積(逆)")
        MyListSub.count += 1
        self.count += 1
        return MyList.__rmull__(self, n)
    def getCount(self):
        print("フックメソッドの呼び出し回数",
              "クラス属性: {0}".format(MyListSub.count),
              "インスタンス属性: {0}".format(self.count),
              sep="\n")
    
if __name__ == '__main__':
    a = MyListSub([1,2,3,4.5])
    b = MyListSub([6,7,8,9,10])
    c = a[:]
    d = a + ['a','b']
    e = ['a','b'] + a
    f = a + b
    g = a[1:5]
    h = a[2]
    
    for x in [a, b, c, d, e, f, g, h]:
        print(x, type(x))
    a.getCount()
    b.getCount()

入出力結果(Terminal)

$ ./sample.py
初期化
初期化
和
和
[1, 2, 3, 4.5] <class '__main__.MyListSub'>
[6, 7, 8, 9, 10] <class '__main__.MyListSub'>
[1, 2, 3, 4.5] <class 'list'>
[1, 2, 3, 4.5, 'a', 'b'] <class '__main__.MyList'>
['a', 'b', 1, 2, 3, 4.5] <class 'list'>
[1, 2, 3, 4.5, 6, 7, 8, 9, 10] <class '__main__.MyList'>
[2, 3, 4.5] <class 'list'>
3 <class 'int'>
フックメソッドの呼び出し回数
クラス属性: 2
インスタンス属性: 2
フックメソッドの呼び出し回数
クラス属性: 2
インスタンス属性: 0
$

0 コメント:

コメントを投稿