開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc.(Text Editor)
- Script言語: Python
『初めての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 __init__(self, data):
list.__init__(self, data)
def __add__(self, y):
return MyList(list.__add__(self, y))
def __getitem__(self, y):
return list.__getitem__(self, y)
def __iadd__(self, y):
return MyList(list.__iadd__(self, y))
def __imul__(self, y):
return MyList(list.__imul__(self, y))
def __mul__(self, n):
return MyList(list.__mul__(self,n))
def __rmul__(self, n):
return MyList(list.__rmul__(self, n))
def copy(self):
return MyList(list.copy(self))
class MyListSub(MyList):
count = 0
def __init__(self, data):
print("コンストラクタ")
self.count = 1
MyListSub.count += 1
MyList.__init__(self, data)
def __add__(self, y):
self.count += 1
MyListSub.count += 1
print("add")
return MyListSub(MyList.__add__(self, y))
def __getitem__(self, y):
self.count += 1
MyListSub.count += 1
return MyList.__getitem__(self, y)
def __iadd__(self, y):
self.count += 1
MyListSub.count += 1
print("iadd")
return MyListSub(MyList.__iadd__(self, y))
def __imul__(self, y):
self.count += 1
MyListSub.count += 1
print("imul")
def __mul__(self, n):
self.count += 1
MyListSub.count += 1
print("mul")
return MyListSub(MyList.__mul__(self, n))
def __rmul__(self, n):
self.count += 1
MyListSub.count += 1
print("rmul")
return MyListSub(MyList.__rmul__(self, n))
def copy(self):
print("copy")
return MyListSub(MyList.copy(self))
def counter(self):
print("インスタンス属性:{0}回, クラス属性:{1}".format(
self.count, MyListSub.count))
a = MyListSub([1,2,3,4,5])
b = MyListSub(['a','b','c','d','e'])
print(a + b)
print(a + ['a','b'])
print([10,100] + b)
a.append("python")
for x in [a, b, a + b, a[:], a[1], b[1]]:
print(x, type(x))
a.counter()
b.counter()
入出力結果(Terminal)
$ ./sample.py コンストラクタ コンストラクタ add コンストラクタ [1, 2, 3, 4, 5, 'a', 'b', 'c', 'd', 'e'] add コンストラクタ [1, 2, 3, 4, 5, 'a', 'b'] [10, 100, 'a', 'b', 'c', 'd', 'e'] add コンストラクタ [1, 2, 3, 4, 5, 'python'] <class '__main__.MyListSub'> ['a', 'b', 'c', 'd', 'e'] <class '__main__.MyListSub'> [1, 2, 3, 4, 5, 'python', 'a', 'b', 'c', 'd', 'e'] <class '__main__.MyListSub'> [1, 2, 3, 4, 5, 'python'] <class 'list'> 2 <class 'int'> b <class 'str'> インスタンス属性:6回, クラス属性:11 インスタンス属性:2回, クラス属性:11 $
0 コメント:
コメントを投稿