開発環境
- 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部(クラスとオブジェクト指向プログラミング)、24章(クラスのコーディング (詳細))の練習問題を解いてみる。
その他参考書籍
1.
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
# 抽象クラス 詳細はサブクラスで定義
class Animal:
def say(self): pass
# 抽象クラスを継承
class Dog(Animal):
def say(self):
print("ワンワン")
class Cat(Animal):
def say(self):
print("ニャーニャー")
dog = Dog()
cat = Cat()
for animal in [dog, cat]:
animal.say()
入出力結果(Terminal)
$ ./sample.py ワンワン ニャーニャー $
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
class A:
def __init__(self, stop):
self.stop = stop
def __getitem__(self, index):
if index < 0 or self.stop <= index:
raise IndexError
return index + 10
a = A(10)
for x in a:
print(x)
入出力結果(Terminal)
$ ./sample.py 10 11 12 13 14 15 16 17 18 19 $
3.
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
class A:
a = 10 # これはクラス属性になる
def f(self):
A.a += 1
i1 = A()
i2 = A()
instances = [i1, i2]
for i in instances:
print(i.a)
i1.f() # クラス属性の値の変更は全てのインスタンスに影響
for i in instances:
print(i.a)
入出力結果(Terminal)
$ ./sample.py 10 10 11 11 $
4.
スーパークラスの__init__メソッドの機能全てを継承して、さらにサブクラスで新たな機能を加えたい場合。
5.
サブクラスのメソッドの中で、Superclass.method(self, ...)と呼び出せばいい。
6.
GenericDisplayクラスの__str__メソッド、gatherAttrsメソッドが動作する。
0 コメント:
コメントを投稿