2012年5月4日金曜日

開発環境

『初めてのPython 第3版』(Mark Lutz 著、夏目 大 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-393-7) のVI部(クラスとオブジェクト指向プログラミング)のまとめ演習6(__bases__属性)を解いてみる。

6.

コード(TextWrangler)

#!/usr/bin/env python
#encoding: utf-8

class Super:
 def __init__(self):
  self.data1 = 10
  self.data2 = 'spam'

class Lister(Super):
 def __repr__(self):
  return ("<Instance of %s(%s), address %s:\n%s>" %
   (self.__class__.__name__,
   self.f(),
   id(self),
   self.attrnames()))
 def attrnames(self):
  result = ''
  for attr in self.__dict__.keys():
   if attr[:2] == '__':
    result += "\tname %s=<built-in\n" % attr
   else:
    result += "\tname %s=%s\n" % (attr,self.__dict__[attr])
  return result
 def f(self):
  result = ''
  i = 1
  for c in self.__class__.__bases__:
   if not i:
    result += ', '
   i = 0
   result += c.__name__
  return result

if __name__ == '__main__':
 print(Lister())

入出力結果(Terminal)

$ python sample.py
<Instance of Lister(Super), address 4366474000:
 name data1=10
 name data2=spam
>
$

0 コメント:

コメントを投稿