開発環境
- 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 3.(Subclassing)を解いてみる。
その他参考書籍
3.(Subclassing)
コード(BBEdit)
sample.py
#!/usr/bin/env python3
#-*- coding: utf-8 -*-
class MyList:
def __init__(self, data=[]):
self.data = list(data)
def __add__(self, other):
if isinstance(other, MyList):
other = other.data
return MyList(self.data + other)
def __radd__(self, other):
return MyList(other + self.data)
def __getitem__(self, i):
return self.data[i]
def append(self, other):
self.data.append(other)
def sort(self,key=None, reverse=False):
self.data.sort(key=key, reverse=reverse)
def __getattr__(self, name):
return getattr(self.data, name)
def __repr__(self):
return 'MyList: {0}'.format(self.data)
class MyListSub(MyList):
count = 0
def __init__(self, data=[]):
self.count = 0
MyList.__init__(self, data)
def __add__(self, other):
print('+ overloaded operation: {0}'.format(other))
MyListSub.count += 1
self.count += 1
return MyList.__add__(self, other)
def counter(self):
print('class: {0}, instance: {1}'.format(MyListSub.count, self.count))
if __name__ == '__main__':
o0 = MyListSub()
o1 = MyListSub([1])
o2 = MyListSub([2,3])
lists = [o0, o1, o2]
new_lists = []
for o in lists:
print(o0 + o)
o0.counter()
o.counter()
for o in lists:
o.counter()
入出力結果(Terminal)
$ ./sample.py + overloaded operation: MyList: [] MyList: [] class: 1, instance: 1 class: 1, instance: 1 + overloaded operation: MyList: [1] MyList: [1] class: 2, instance: 2 class: 2, instance: 0 + overloaded operation: MyList: [2, 3] MyList: [2, 3] class: 3, instance: 3 class: 3, instance: 0 class: 3, instance: 3 class: 3, instance: 0 class: 3, instance: 0 $
0 コメント:
コメントを投稿