「大人の教養・知識・気付き」を伸ばすブログ

一流の大人(ビジネスマン、政治家、リーダー…)として知っておきたい、教養・社会動向を意外なところから取り上げ学ぶことで“気付く力”を伸ばすブログです。データ分析・語学に力点を置いています。 →現在、コンサルタントの雛になるべく、少しずつ勉強中です(※2024年1月21日改訂)。

MENU

Pythonをゆっくりていねいに学ぶ(その16/X)

 Pythonを真面目にゆっくり学ぶべく

を参考に学んでいきます*1

6. オブジェクトとクラス

6.7 特殊メソッド

 応用的なメソッドを考える。特殊メソッドの名称は先頭と末尾にダブルアンダースコア(__)を用いる。

比較用の特殊メソッド 意味
__\mathrm{eq}__(\mathrm{self},\mathrm{other}) \mathrm{self}\ ==\ \mathrm{other}
__\mathrm{ne}__(\mathrm{self},\mathrm{other}) \mathrm{self}!\mathrm{other}
__\mathrm{lt}__(\mathrm{self},\mathrm{other}) \mathrm{self}\lt\mathrm{other}
__\mathrm{gt}__(\mathrm{self},\mathrm{other}) \mathrm{self}\gt\mathrm{other}
__\mathrm{le}__(\mathrm{self},\mathrm{other}) \mathrm{self}\lt=\mathrm{other}
__\mathrm{ge}__(\mathrm{self},\mathrm{other}) \mathrm{self}\gt=\mathrm{other}
算術計算用の特殊メソッド 意味
__\mathrm{add}__(\mathrm{self},\mathrm{other}) \mathrm{self}+\mathrm{other}
__\mathrm{sub}__(\mathrm{self},\mathrm{other}) \mathrm{self}-\mathrm{other}
__\mathrm{mul}__(\mathrm{self},\mathrm{other}) \mathrm{self}*\mathrm{other}
__\mathrm{floordiv}__(\mathrm{self},\mathrm{other}) \mathrm{self}//\mathrm{other}
__\mathrm{truediv}__(\mathrm{self},\mathrm{other}) \mathrm{self}/\mathrm{other}
__\mathrm{mod}__(\mathrm{self},\mathrm{other}) \mathrm{self}%\mathrm{other}
__\mathrm{pow}__(\mathrm{self},\mathrm{other}) \mathrm{self}**\mathrm{other}
その他特殊メソッド 意味
__\mathrm{str}__(\mathrm{self}) \mathrm{str(self)}
__\mathrm{repr}__(\mathrm{self}) \mathrm{repr(self)}
__\mathrm{len}__(\mathrm{self}) \mathrm{len(self)}
class Word():
    def __init__(self, text):
        self.text = text
    def __eq__(self, word2):
        return self.text.lower() == word2.text.lower()
    def __str__(self):
        return self.text
    def __repr__(self):
        return 'Word("' + self.text + '")'
first = Word('ha')

print(first)
first

6.8 コンポジション

 継承よりもコンポジションや集約の方が理にかなっているケースがあり得る。

class Bill():
    def __init__(self, description):
        self.description = description
class Tail():
    def __init__(self, length):
        self.length = length
class Duck():
    def __init__(self, bill, tail):
        self.bill = bill
        self.tail = tail
    def about(self):
        print('This duck has a', self.bill.description, 'bill and a', self.tail.length, 'tail')

tail = Tail('long')
bill = Bill('wide orange')
duck = Duck(bill, tail)

duck.about()

6.9 クラスとオブジェクトを用いるべきとき

 

  • 動作(メソッド)は同じだが、内部状態(属性)は異なる複数のインスタンスを必要とする
  • クラスは継承をサポートする。モジュールは継承をサポートしない。
  • 何かを1つだけ必要とされる場合、モジュールの方が良い。
  • 複数の値を持つ変数があり、これらを複数の関数に引数として渡す場合、それをクラスとして定義した方が良い。
  • 問題に取って最も単純な方法を用いる。辞書、リストおよびタプルはモジュールよりも単純で小さく高速であり、クラスよりも単純なのが普通である。
6.9.1 名前付きタプル
from collections import namedtuple
Duck = namedtuple('Duck', 'bill tail')
duck = Duck('wild orange', 'long')

print(duck)
print(duck.bill)
print(duck.tail)

*1:第2版が出ているものの初版しか持っていないのでこちらで。

プライバシーポリシー お問い合わせ