開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- Python (プログラミング言語)
Learning Python (Mark Lutz (著)、Oreilly & Associates Inc)のPART Ⅵ.(Classes and OOP)、CHAPTER 32(Advanced Class Topics)、Test Your Knowledge: Part VI Exercises 1.(Inheritance)を解いてみる。
その他参考書籍
1.(Inheritance)
コード(BBEdit)
sample.py
#!/usr/bin/env python3 #-*- 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): res = {} for k, v in x.items(): res[k] = v for k, v in y.items(): res[k] = v return res class Adder1: def __init__(self, data): self.data = data def add(self, x, y): print('Not implemented') def __add__(self, other): if isinstance(other, self.__class__): other = other.data return self.add(self.data, other) class ListAdder1(Adder1): def add(self, x, y): return x + y class DictAdder1(Adder1): def add(self, x, y): res = {} for k, v in x.items(): res[k] = v for k, v in y.items(): res[k] = v return res if __name__ == '__main__': a = Adder() b = ListAdder() c = DictAdder() a.add('python', 10) print(b.add([1,2], [3,4,5])) print(c.add({'a':1, 'b':2}, {'c':3, 'd':4, 'e':5})) a = Adder1("python") b = Adder1(10) c = ListAdder1([1,2]) d = ListAdder1([3,4,5]) e = DictAdder1({'a':1, 'b':2}) f = DictAdder1({'c':3, 'd':4, 'e':5}) t = a + b t = a + 10 print(c + d) print(c + [3,4,5]) print(e + f) print(e + {'c':3, 'd':4, 'e':5})
入出力結果(Terminal)
./sample.py Not implemented [1, 2, 3, 4, 5] {'b': 2, 'c': 3, 'd': 4, 'e': 5, 'a': 1} Not implemented Not implemented [1, 2, 3, 4, 5] [1, 2, 3, 4, 5] {'b': 2, 'c': 3, 'd': 4, 'e': 5, 'a': 1} {'b': 2, 'c': 3, 'd': 4, 'e': 5, 'a': 1} $
0 コメント:
コメントを投稿