開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの無料機能制限版、light版)
- Script言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のVI部(クラスとオブジェクト指向プログラミング)のまとめ演習1(継承)を解いてみる。
その他参考書籍
1.
コード(TextWrangler)
sample.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Adder:
def add(self,x,y):
print("Not Implemented")
class ListAdder(Adder):
def add(self,a,b):
return a + b
class DictAdder(Adder):
def add(self,a,b):
result = {}
for key in a.keys():
result[key] = a[key]
for key in b.keys():
result[key] = b[key]
return result
入出力結果(Terminal)
$ python
Python 3.2.3 (default, Apr 18 2012, 20:17:30)
[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.
>>> import sample as s
>>> a = s.Adder()
>>> b=s.ListAdder()
>>> c=s.DictAdder()
>>> a.add(1,2)
Not Implemented
>>> b.add([1,2],[3,4,5])
[1, 2, 3, 4, 5]
>>> c.add({'a':1,'b':2},{'c':3,'d':4,'e':5})
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
>>> quit()
$
改造
コード(TextWrangler)
sample.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Adder:
def __init__(self,data):
self.data = data
def add(self,x):
print("Not Implemented")
def __add__(self,other):
return self.add(other)
class ListAdder(Adder):
def add(self,other):
return self.data + other
class DictAdder(Adder):
def add(self,other):
result = {}
for key in self.data.keys():
result[key] = self.data[key]
for key in other.keys():
result[key] = other[key]
return result
if __name__ == "__main__":
a = Adder(10)
print(a + 20)
b = ListAdder([1,2])
print(b + [3,4,5])
c = DictAdder({'a':1,'b':2})
print(c + {'c':3,'d':4,'e':5})
$
コード(TextWrangler)
sample.py
$ ./sample.py
Not Implemented
None
[1, 2, 3, 4, 5]
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
$
0 コメント:
コメントを投稿