2012年4月30日月曜日

開発環境

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

2.

コード(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 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])

if __name__ == '__main__':
 a = MyList([5,1,4,2,3])
 print(a)
 print(a + [7,8,9,10])
 for x in a:
  print(x)
 print(a[1:3])
 a.append(10)
 print(a)
 a.sort()
 print(a)

入出力結果(Terminal)

$ python sample.py
[5, 1, 4, 2, 3]
[5, 1, 4, 2, 3, 7, 8, 9, 10]
5
1
4
2
3
[1, 4]
[5, 1, 4, 2, 3, 10]
[1, 2, 3, 4, 5, 10]
$

0 コメント:

コメントを投稿