開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Python
『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7)のIV部(クラスとオブジェクト指向プログラミング)、まとめ演習1.(継承)を解いてみる。
その他参考書籍
まとめ演習1.(継承)
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
入出力結果(Terminal)
$ python
Python 3.3.1 (default, Apr 6 2013, 12:29:18)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from sample import *
>>> a=Adder()
>>> b=ListAdder()
>>> c=DictAdder()
>>> a.add(5,10)
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}
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
class Adder:
def __init__(self, data):
self.data = data
def __add__(self, y):
return self.add(y)
def add(self, y):
print("Not Implemented")
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
if __name__ == '__main__':
a = ListAdder([1,2])
b = DictAdder({'a':1,'b':2})
print(a + [3,4,5])
print(b + {'c':3,'d':4,'e':5})
入出力結果(Terminal)
$ ./sample.py
[1, 2, 3, 4, 5]
{'d': 4, 'e': 5, 'a': 1, 'b': 2, 'c': 3}
$
0 コメント:
コメントを投稿