Python15分講座 #4 ダックタイピング

"If it walks like a duck and quacks like a duck, it must be a duck"
(もしもそれがアヒルのように歩き、アヒルのように鳴くのなら、それはアヒルである)

# 実装が同じクラスA,Bを定義

>>> class A(object):
	def printType(self):
		print('type' + type(self))

		
>>> class B(object):
	def printType(self):
		print('hogehoge : ' + str(type(self)))

		
# それぞれ実行してみる
>>> a = A()
>>> a.printType()


type : <class '__main__.A'>

>>> b = B()
>>> b.printType()


hogehoge : <class '__main__.B'>

# 当然の結果
# リストにインスタンスa, bを追加
>>> list = []
>>> list.append(a)
>>> list.append(b)

# ループで実行
>>> for hoge in list:
	hoge.printType()

	

type : <class '__main__.A'>
hogehoge : <class '__main__.B'>


Javaでいうインタフェースを実装する必要がありません。


"アヒルのように鳴くならそれはアヒルだ"

つまり。。。

// Javaのコード
interface 福本 {
    void カイジっぽく鳴く();
}


public class カイジ implements 福本 {
    public void カイジっぽく鳴く(){
        System.out.println("ざわ...ざわ...");
    }
}


Javaならこんな感じにするかと思いますが、
ダックタイピングの考え方では、"カイジっぽく鳴く"なら
それは福本インタフェースを実装しているものとみなす。
いいじゃんカイジで。

・・・と。


動的型付け言語のやわらかい部分を勉強しました。