開発環境
- 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部(オブジェクト指向プログラミング)のまとめ演習2.(リストの機能のオーバーロード)を解いてみる。
その他参考書籍
2.(リストの機能のオーバーロード)
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
# メッセージを表示するようにリストのいくつかの機能をオーバーロードしてみる
class MyList(list):
def __init__(self, data):
print("コンストラクタ")
list.__init__(self, data)
def __add__(self, y):
print("add")
return MyList(list.__add__(self, y))
def __iadd(self, y):
print("iadd")
return MyList(list.__iadd__(self, y))
def __imul__(self, y):
print("imul")
return MyList(list.__imul__(self, y))
def __mul__(self, n):
print("mul")
return MyList(list.__mul__(self,n))
def __rmul__(self, n):
print("rmul")
return MyList(list.__rmul__(self, n))
def __iter__(self):
return MyList(list.__iter__(self))
def copy(self):
print("copy")
return MyList(list.copy(self))
a = MyList([1,2,3,4,5])
b = MyList(['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))
入出力結果(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__.MyList'> ['a', 'b', 'c', 'd', 'e'] <class '__main__.MyList'> [1, 2, 3, 4, 5, 'python', 'a', 'b', 'c', 'd', 'e'] <class '__main__.MyList'> [1, 2, 3, 4, 5, 'python'] <class 'list'> 2 <class 'int'> b <class 'str'> $
0 コメント:
コメントを投稿