開発環境
- 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)
#!/usr/bin/env python #encoding: utf-8 class Adder: def add(self, x, y): print("Not Implement") class ListAdder(Adder): def add(self, x, y): return x + y class DictAdder(Adder): def add(self,x, y): result = {} for key in x.keys(): result[key] = x[key] for key in y.keys(): result[key] = y[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. >>> from sample import * >>> a=Adder() >>> b=ListAdder() >>> c=DictAdder() >>> a.add(1,2) Not Implement >>> b.add([1,2],[3,4,5,6]) [1, 2, 3, 4, 5, 6] >>> c.add({'a':1,'b':2},{'c':3,'d':4,'e':5}) {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} >>> quit() $
改造
コード(TextWrangler)
#!/usr/bin/env python #encoding: utf-8 class Adder: def __init__(self,data = []): self.data = data def __add__(self,other): return self.add(self.data,other) def add(self, x, y): print("Not Implement") class ListAdder(Adder): def add(self, x, y): return x + y class DictAdder(Adder): def add(self,x, y): result = {} for key in x.keys(): result[key] = x[key] for key in y.keys(): result[key] = y[key] return result if __name__ == '__main__': l1 = [1,2] l2 = [3,4,5] a = Adder(l1) a + l2 b = ListAdder(l1) print(l1 + l2)
入出力結果(Terminal)
$ python sample.py Not Implement [1, 2, 3, 4, 5] $
0 コメント:
コメントを投稿