開発環境
- 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)
#!/usr/bin/env python #encoding: 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,index): return self.data[index] def __len__(self): return len(self.data) def append(self,item): self.data.append(item) def sort(self): self.data.sort() def __repr__(self): return repr(self.data) def index(self,start,stop): return MyList(self.data[start:stop]) class MyListSub(MyList): count = 0 def __init__(self,data): MyListSub.count += 1 self.count = 0 MyList.__init__(self,data) def __add__(self,other): MyListSub.count += 1 self.count += 1 MyList.__add__(self,other) def __getitem__(self,index): MyListSub.count += 1 self.count += 1 MyList.__getitem__(self,index) def __len__(self,data): MyListSub.count += 1 self.count += 1 MyList.__len__(self,data) def __repr__(self): MyListSub.count += 1 self.count += 1 MyList.__repr(self) def f(self): return MyListSub.count, self.count if __name__ == '__main__': a = MyListSub('spam') b = MyListSub('eggs') for x in a:pass b[1] b[1:2] print(a.f(),b.f())
入出力結果(Terminal)
$ python sample.py (9, 5) (9, 2) $
0 コメント:
コメントを投稿