| ページ一覧 | ブログ | twitter |  書式 | 書式(表) |

MyMemoWiki

Python サンプルコード オブジェクト指向

提供: MyMemoWiki
ナビゲーションに移動 検索に移動

Python サンプルコード オブジェクト指向

Python | Python サンプルコード | 言語まとめ Python | Python 標準ライブラリ概観 |

クラスを使用

API 概要
class クラス名: クラスを作成
def メソッド名(self,引数・・・) メンバ関数
def __init__(self) インスタンス初期化
  • メンバ関数の先頭引数にはインスタンスの参照(self)を指定する
  • クラス名()でインスタンスを作成
  1. class Person:
  2. def __init__(self):
  3. print 'wake up'
  4.  
  5. def greet(self):
  6. print 'hello.'
  7.  
  8. x = Person()
  9. x.greet()
結果
  1. wake up
  2. hello.

新スタイルクラスとクラシッククラス

  • Version2.2以降、「新スタイルクラス」が利用可能

<blockquote>「新スタイルクラス」は、__ビルトインオブジェクト(list、object等)のサブクラスとして作成する__(ビルトインオブジェクトのサブクラスは自動的に新スタイルとなる)</blockquote>

  1. # 新スタイルクラス
  2. class NewStyle(object):
  3. pass
  4.  
  5. # クラシックスタイルクラス
  6. class OldStyle:
  7. pass

ダイヤモンド継承時の属性検索順序

  • 新スタイルクラスとクラシッククラスでは、ダイヤモンド継承時の属性検索順序が異なる
クラシッククラス
  • 属性の検索順序は以下の順序にて行われる
    1. 下から上
    2. 左から右(基底クラスの記述順)
  • 検索順(C3よりC1のほうが優先される)

1023 py classic cls search.jpg

  1. class C1:
  2. def m1(self):
  3. print 'C1'
  4. class C2(C1):
  5. pass
  6. class C3(C1):
  7. def m1(self):
  8. print 'C3'
  9. class C4(C2,C3): pass
  10. c = C4()
  11. c.m1()
  • 結果
  1. C1
新スタイルクラス
  • 属性の検索順序は以下の順序にて行われる
    1. 左から右(基底クラスの記述順)
    2. 下から上
  • 検索順(C1よりC3のほうが優先される)

1024 py new cls search.jpg

  1. class C1(object):
  2. def m1(self):
  3. print 'C1'
  4. class C2(C1):
  5. pass
  6. class C3(C1):
  7. def m1(self):
  8. print 'C3'
  9.  
  10. class C4(C2,C3): pass
  11. c = C4()
  12. c.m1()
  • 結果
  1. C3

コンストラクタ

基底クラスのコンストラクタを呼び出す

  1. # -*- coding: utf-8 -*-
  2.  
  3. class Base(object):
  4. def __init__(self, x):
  5. self.x = x
  6. def get_v(self):
  7. return self.x
  8.  
  9. class Deriv(Base):
  10. def __init__(self, x):
  11. # 基底クラスのコンストラクタを呼び出す
  12. super(Deriv, self).__init__(x)
  13. def get_x(self):
  14. # 基底クラスを指定してメソッドを呼び出す
  15. return super(Deriv, self).get_v()
  16.  
  17. b = Base('base')
  18. print b.get_v()
  19.  
  20. d = Deriv('deriv')
  21. print d.get_v()
  22. print d.get_x()
  23.  
結果
  1. base
  2. deriv
  3. deriv

カプセル化

プロパティ

通常の記法
  1. class Spam(object):
  2. def __init__(self):
  3. self.__ham = 'spam.ham'
  4. def get_ham(self):
  5. return self.__ham
  6. def set_ham(self, value):
  7. self.__ham = value
  8. def del_ham(self):
  9. del self.__ham
  10. ham = property(get_ham, set_ham, del_ham, 'ham property')
関数デコレータ使用
  1. class Egg(object):
  2. def __init__(self):
  3. self.__ham = 'egg.ham'
  4. @property
  5. def ham(self):
  6. return self.__ham
  7. @ham.setter
  8. def ham(self, value):
  9. self.__ham = value
  10. @ham.deleter
  11. def ham(self):
  12. del self.__ham

メソッドオブジェクト

メソッドをオブジェクトとして扱う
  1. class Person:
  2. def greet(self):
  3. print 'hello.'
  4.  
  5. x = Person()
  6. y = x.greet
  7.  
  8. print type(y)
  9. y()
  10.  
結果
  1. <type 'instancemethod'>
  2. hello.

インスタンスと結びついている

  1. >>> class Foo:
  2. ... f1 =
  3. ... def bar(self, msg):
  4. ... print msg
  5. ... self.f1 = 'called'
  6. ... def status(self):
  7. ... print self.f1
  8. ...
  9. >>> f = Foo()
  10. >>> x = f.bar
  11. >>> x('test')
  12. test
  13. >>> f.status()
  14. called

継承

API 概要
class 派生クラス名(基底クラス名): 基底クラスから派生クラスを作成
  1. class Person(object):
  2. def __init__(self):
  3. self._msg = '...'
  4. def greet(self):
  5. print self._msg
  6.  
  7. class Japanese(Person):
  8. def __init__(self):
  9. self._msg = 'ohayo-'
  10.  
  11. class American(Person):
  12. def __init__(self):
  13. self._msg = 'hello'
結果
  1. >>> x = Japanese()
  2. >>> x.greet()
  3. ohayo-
  4. >>> y = American()
  5. >>> y.greet()
  6. hello
  7. >>> z = Person()
  8. >>> z.greet()
  9. ...

多重継承

API 概要
class 派生クラス名(基底クラス名,基底クラス名,・・・): 基底クラス(複数)から派生クラスを多重継承して作成
pass 処理がないのを明示
  1. class Person:
  2. def speak(self):
  3. print 'hello'
  4.  
  5. class Bird:
  6. def fly(self):
  7. print 'flying in the sky'
  8.  
  9. class BirdMan(Person, Bird):
  10. pass
  11.  
  12. x = BirdMan()
  13. x.speak()
  14. x.fly()

ポリモーフィズム

  1. class Animal:
  2. voice = '...'
  3. def cry(self):
  4. print self.voice
  5.  
  6. class Cat(Animal):
  7. voice = 'nya-'
  8.  
  9. class Dog(Animal):
  10. voice = 'wan'
  11.  
  12. c = Cat()
  13. d = Dog()
  14.  
  15. mypet = [c, d]
  16. for pet in mypet:
  17. pet.cry()
結果
  1. nya-
  2. wan

クラスのインスタンスかを調べる

インスタンスが指定の型か調べる

  • isinstance()を使用する
  1. >>> l = ['a','b','c']
  2. >>> isinstance(l, list)
  3. True

インスタンスが指定の型か同時に調べる

  • 調査する型にタプルを指定
  1. >>> t = (1,2,3)
  2. >>> isinstance(t, (list, tupli))
  3. >>> isinstance(t, (list, tuple))
  4. True

クラスのサブクラスかを調べる

  • issubclass()を使用する
  • 複数同時に調べる場合、タプルを指定
  1. >>> class base_cls1:
  2. ... pass
  3. ...
  4. >>> class base_cls2:
  5. ... pass
  6. ...
  7. >>> class driv_cls(base_cls1, base_cls2):
  8. ... pass
  9. ...
  10. >>> c = driv_cls()
  11. >>> isinstance(c, (base_cls1, base_cls2))
  12. True
  13. >>> issubclass(driv_cls, (base_cls1, base_cls2))
  14. True