開発環境
- 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 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)
class MylistSub(Mylist):
count = 0
def __init__(self, data):
self.add = 0
self.mul = 0
self.getslice = 0
Mylist.__init__(self,data)
def __add__(self, other):
MylistSub.count += 1
self.add += 1
return Mylist.__add__(self,other)
def __mul__(self,other):
MylistSub.count += 1
self.mul += 1
return Mylist.__mul__(self,other)
def __getslice__(self,start,end):
MylistSub.count += 1
self.getslice += 1
return Mylist.__getslice__(self,start,end)
def p(self):
print self.count,self.add,self.mul,self.getslice
入出力結果(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=MylistSub('python')
>>> print a
['p', 'y', 't', 'h', 'o', 'n']
>>> a.p()
0 0 0 0
>>> print a + ['kamimura']
['p', 'y', 't', 'h', 'o', 'n', 'kamimura']
>>> a.p()
1 1 0 0
>>> print a*5
['p', 'y', 't', 'h', 'o', 'n', 'p', 'y', 't', 'h', 'o', 'n', 'p', 'y', 't', 'h', 'o', 'n', 'p', 'y', 't', 'h', 'o', 'n', 'p', 'y', 't', 'h', 'o', 'n']
>>> a.p()
2 1 1 0
>>> print a[1:4]
['y', 't', 'h']
>>> a.p()
3 1 1 1
>>> ^D
$
こんな感じでいいのかな。
0 コメント:
コメントを投稿