開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
- Script言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のVI部(クラスとオブジェクト指向プログラミング)のまとめ演習3(サブクラスの作成)を解いてみる。
その他参考書籍
3.
コード(TextWrangler)
sample.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class MyList:
def __init__(self,data):
self.data = []
for x in data:
self.data.append(x)
def __add__(self,other):
return MyList(self.data + other)
def __getitem__(self,offset):
return self.data[offset]
def __len__(self):
return len(self.data)
def append(self,x):
self.data.append(x)
def sort(self):
self.data.sort()
def __repr__(self):
return repr(self.data)
def __str__(self):
return str(self.data)
class MyListSub(MyList):
count = 0
def __init__(self,data):
self.count = 0
MyList.__init__(self,data)
def __add__(self,other):
self.counter()
self.status()
return MyList.__add__(self, other)
def __getitem__(self,offset):
self.counter()
self.status()
return MyList.__getitem__(self,offset)
def __len__(self):
self.counter()
self.status()
return MyList.__len__(self)
def __repr__(self):
self.counter()
self.status()
return NyList.__repr__(self)
def __str__(self):
self.counter()
self.status()
return MyList.__str__(self)
def counter(self):
MyListSub.count += 1
self.count += 1
def status(self):
print("クラス属性: " + str(MyListSub.count) + "回, "+
"インスタンス属性: " + str(self.count) + "回")
if __name__ == "__main__":
a = MyListSub([5,1,4,2,3])
b = MyListSub("kamimura")
print(a)
print(b)
print(a + [1,2,3,4,5])
print(b + [1,2,3,4,5])
for x in [a,b]:
print(x[1])
for x in [a,b]:
for y in x:
print(y)
print()
for x in [a,b]:
print(x[1:4])
a.append(100)
b.append('python')
for x in [a,b]:
print(x)
for x in [a,b]:
x.sort()
print(x)
入出力結果(Terminal)
$ ./sample.py クラス属性: 1回, インスタンス属性: 1回 [5, 1, 4, 2, 3] クラス属性: 2回, インスタンス属性: 1回 ['k', 'a', 'm', 'i', 'm', 'u', 'r', 'a'] クラス属性: 3回, インスタンス属性: 2回 [5, 1, 4, 2, 3, 1, 2, 3, 4, 5] クラス属性: 4回, インスタンス属性: 2回 ['k', 'a', 'm', 'i', 'm', 'u', 'r', 'a', 1, 2, 3, 4, 5] クラス属性: 5回, インスタンス属性: 3回 1 クラス属性: 6回, インスタンス属性: 3回 a クラス属性: 7回, インスタンス属性: 4回 5 クラス属性: 8回, インスタンス属性: 5回 1 クラス属性: 9回, インスタンス属性: 6回 4 クラス属性: 10回, インスタンス属性: 7回 2 クラス属性: 11回, インスタンス属性: 8回 3 クラス属性: 12回, インスタンス属性: 9回 クラス属性: 13回, インスタンス属性: 4回 k クラス属性: 14回, インスタンス属性: 5回 a クラス属性: 15回, インスタンス属性: 6回 m クラス属性: 16回, インスタンス属性: 7回 i クラス属性: 17回, インスタンス属性: 8回 m クラス属性: 18回, インスタンス属性: 9回 u クラス属性: 19回, インスタンス属性: 10回 r クラス属性: 20回, インスタンス属性: 11回 a クラス属性: 21回, インスタンス属性: 12回 クラス属性: 22回, インスタンス属性: 10回 [1, 4, 2] クラス属性: 23回, インスタンス属性: 13回 ['a', 'm', 'i'] クラス属性: 24回, インスタンス属性: 11回 [5, 1, 4, 2, 3, 100] クラス属性: 25回, インスタンス属性: 14回 ['k', 'a', 'm', 'i', 'm', 'u', 'r', 'a', 'python'] クラス属性: 26回, インスタンス属性: 12回 [1, 2, 3, 4, 5, 100] クラス属性: 27回, インスタンス属性: 15回 ['a', 'a', 'i', 'k', 'm', 'm', 'python', 'r', 'u'] $
0 コメント:
コメントを投稿