開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
- Script言語: Python
『初めての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 a in data: self.data.append(a) def __add__(self,other): return MyList(self.data + other) def __mul__(self,other): return MyList(self.data * other) def __getitem__(self, index): return self.data[index] def __getslice__(self,start,end): return MyList(self.data[start:end]) def append(self,other): self.data.append(other) def __getattr__(self,name): return getattr(self.data,name) def __repr__(self): return repr(self,data)
入出力結果(Terminal)
$ python
Python 2.7.2 (default, Feb 12 2012, 23:50:38)
[GCC 4.2.1 Compatible Apple Clang 3.0 (tags/Apple/clang-211.12)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from python_program import *
>>> a=MyList('python')
>>> print a
['p', 'y', 't', 'h', 'o', 'n']
>>> print a+['kamimura']
['p', 'y', 't', 'h', 'o', 'n', 'kamimura']
>>> print a[1]
y
>>> for x in a:
... print x
...
p
y
t
h
o
n
>>> print a[1:4]
['y', 't', 'h']
>>> a.append(' other')
>>> print a
['p', 'y', 't', 'h', 'o', 'n', ' other']
>>> a.sort()
>>> print a
[' other', 'h', 'n', 'o', 'p', 't', 'y']
>>> a.reverse()
>>> print a
['y', 't', 'p', 'o', 'n', 'h', ' other']
>>> ^D
$
こんな感じでいいのかな。
0 コメント:
コメントを投稿