開発環境
- 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部(クラスとオブジェクト指向プログラミング)のまとめ演習6.(__bases__属性)を解いてみる。
その他参考書籍
6.(__bases__属性)
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
class Lister:
def __repr__(self):
supers = self.getSuperclasses()
if supers:
return ("<Instance of {0}({1}), address {2}:\n{3}>".format(
self.__class__.__name__, supers, id(self), self.attrnames()))
else:
return ("<Instance of {0}, address {1}:\n{2}>".format(
self.__class__.__name__, id(self), self.attrnames()))
def attrnames(self):
result = ""
for attr in self.__dict__:
if attr[:2] == '__':
result += "\tname {0}=<built-in>\n".format(attr)
else:
result += "\tname {0}={1}\n".format(
attr, self.__dict__[attr])
return result
def getSuperclasses(self):
supers = [x.__name__ for x in self.__class__.__bases__]
return ", ".join(supers)
class Super(Lister):
def __init__(self):
self.data1 = "spam"
class Sub(Super, Lister):
def __init__(self):
Super.__init__(self)
self.data2 = "eggs"
self.data3 = 42
if __name__ == '__main__':
a = Lister()
b = Super()
c = Sub()
o = object()
print(a, b, c, o, sep="\n")
入出力結果(Terminal)
$ ./sample.py <Instance of Lister(object), address 4354916112: > <Instance of Super(Lister), address 4354916176: name data1=spam > <Instance of Sub(Super, Lister), address 4354916240: name data3=42 name data2=eggs name data1=spam > <object object at 0x10383e080> $
0 コメント:
コメントを投稿