LoginSignup
2
3

More than 3 years have passed since last update.

Python でクラス作成してダックタイピングしてみた

Posted at

人間クラスと継承、車のクラスで判定

ダックテストというものがあるらしい。Wikipedia様の情報によりますと
"If it walks like a duck and quacks like a duck, it must be a duck"
「もしもそれがアヒルのように歩き、アヒルのように鳴くのなら、それはアヒルに違いない」
という考え方のようです。ここから来たのがダックタイピング。

ダックタイピングは例えばRubyだとこんな感じとなります。

Ruby でのダックタイピング

sampleRuby.rb
# テスト
def test(foo)
   puts foo.sound
end

# アヒルの鳴き声
 class Duck
   def sound
     'quack'
   end
 end
 # 猫の鳴き声
 class Cat
   def sound
     'myaa'
   end
 end
 # 実行
 test(Duck.new)
 test(Cat.new)

出力は

# 出力結果
quack
myaa

要するに、クラスが別であっても同じ名前のメソッドを使用することができ、異なるオブジェクトで同じ操作を切り替えて使うことができるというもののようです。

例えば、人間クラスを若者と大人が継承して、それを車クラスで判定して、ドライバーの資格があるかどうか判定をするとします。
例えば以下のようなサンプルコードはどうでしょう。Pythonです。

Python でのダックタイピング

samplePython.py
#
# 人間のクラス
#  2020.07.24 ProOJI
#
class Person(object):
    """年齢メソッド"""
    def __init__(self, age=1):
        self.age = age
    """ドライバー資格メソッド"""
    def drive(self):
        if self.age >= 18:
            print('You can drive!')
            print("Because You're {} years old.".format(self.age))
        else:
            raise Exception('Sorry...you cannot drive.')
# 若者のクラス
class Young(Person):
    def __init__(self, age=12):
        if age < 18:
            super().__init__(age)
        else:
            raise ValueError
# 大人のクラス
class Adult(Person):
    def __init__(self, age=18):
        if age >= 18:
            super().__init__(age)
        else:
            raise ValueError
#
# 自動車クラス
#  ドライバー資格の判定
class Car(object):
    def __init__(self, model=None):
        self.model = model
    def ride(self, person):
        person.drive()

# 若者_インスタンスの生成(13歳)
young = Young(13)
# 大人_インスタンスの生成(46歳)
adult = Adult(46)
# 自動車_インスタンスの生成_1
car = Car()
# 若者の判定 13歳
car.ride(young)
# 出力結果
# Exception: Sorry...you cannot drive.
# 自動車_インスタンスの生成_2
car = Car()
# 若者の判定 46歳
car.ride(adult)
# 出力結果
# You can drive!
# Because You're 46 years old.

まとめ

プログラミングにはポリモーフィズムという概念があり、日本語では多態性・多様性など言われます。これはオブジェクト指向の概念の一つです。
クラスの型が別であっても同じ名前のメソッドがあればそれを使用することができ、異なるオブジェクトで同じ操作を切り替えて使うことができます。
このようなコードをダックタイピング(duck typing)と言うことがわかりました。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3