開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: 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 add(self, x, y):
print("Not implemented")
class ListAdder(Adder):
def add(self, x, y):
return x + y
class DictAdder(Adder):
def add(self, x, y):
x.update(y)
return x
a = ListAdder()
b = DictAdder()
print(a.add([1,2], [3,4,5]),
b.add({'a':1,'b':2}, {'c':3,'d':4,'e':5}), sep="\n")
入出力結果(Terminal)
$ ./sample.py
[1, 2, 3, 4, 5]
{'e': 5, 'd': 4, 'c': 3, 'b': 2, 'a': 1}
$
改造後
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
class Adder:
def __init__(self, data):
self.data = data
def add(self, y):
print("Not implemented")
def __add__(self, y):
return self.add(y)
class ListAdder(Adder):
def add(self, y):
return self.data + y
class DictAdder(Adder):
def add(self, y):
self.data.update(y)
return self.data
a = ListAdder([1,2])
b = DictAdder({'a':1,'b':2})
print(a + [3,4,5], b + {'c':3,'d':4,'e':5}, sep="\n")
入出力結果(Terminal)
$ ./sample.py
[1, 2, 3, 4, 5]
{'b': 2, 'c': 3, 'a': 1, 'd': 4, 'e': 5}
$
0 コメント:
コメントを投稿