開発環境
- 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部(オブジェクト指向プログラミング)のまとめ演習1.(継承)を解いてみる。
その他参考書籍
1.(継承)
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 #-*- 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.data + other class ListAdder(Adder): def add(self, other): return self.data + other class DictAdder(Adder): def add(self, other): res = {} for k, v in self.data.items(): res[k] = v for k, v in other.items(): res[k] = v return res if __name__ == '__main__': a = Adder(10) b = ListAdder([1,2,3,4,5]) c = DictAdder({'a':1,'b':2}) for x, y in [(a, 20), (b, [6,7]), (c, {"c":3,'d':4,'e':5})]: print(x.add(y)) if not type(x) == DictAdder: print(x + y)
入出力結果(Terminal)
#!/usr/bin/env python3.3 #-*- 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.data + other class ListAdder(Adder): def add(self, other): return self.data + other class DictAdder(Adder): def add(self, other): res = {} for k, v in self.data.items(): res[k] = v for k, v in other.items(): res[k] = v return res if __name__ == '__main__': a = Adder(10) b = ListAdder([1,2,3,4,5]) c = DictAdder({'a':1,'b':2}) for x, y in [(a, 20), (b, [6,7]), (c, {"c":3,'d':4,'e':5})]: print(x.add(y)) if not type(x) == DictAdder: print(x + y)
ちなみにJavaScriptの場合。
コード(BBEdit)
var Adder = function(data){ this.data = data; }; Adder.prototype.add = function(x, y){ $('#pre0').append("Not implemented\n"); }; var ArrayAdder = function(data){ Adder.apply(this,[data]); }; ArrayAdder.prototype = new Adder(); ArrayAdder.prototype.add = function(o){ return this.data.concat(o); }; var DictAdder = function(data){ Adder.apply(this,[data]); }; DictAdder.prototype = new Adder(); DictAdder.prototype.add = function(o){ var res = {}; for(var p in this.data){ res[p] = this.data[p]; } for(var p in o){ res[p] = o[p]; } return res; }; var a = new Adder(10); var b = new ArrayAdder([1,2]); var c = new DictAdder({'a':1,'b':2}); a.add(20); $('#pre0').append(b.add([3,4,5]) + "\n"); var d = c.add({'c':3,'d':4,'e':5}); for(var p in d){ $('#pre0').append(p + ": " + d[p] + "\n"); }
0 コメント:
コメントを投稿