3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Pythonのダックタイピング(duck typing)を理解する

Posted at

”If it walks like a duck and quacks like a duck, it must be a duck”

Pythonに限らず、プログラミングにはポリモーフィズムという概念があります。これはオブジェクト指向プログラミングの概念の一つで、日本語では多態性・多様性など言われています。

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

このようなコードをダックタイピング(duck typing)などと言います。


class Animal(object):
    def run(self):
        print('Animal is running...')
class Dog(Animal):
    def run(self):
        print('Dog is running...')
class Cat(Animal):

    def run(self):
        print('Cat is running...')
class people():           #ご注目してください、Amimalのサブクラスではありません
    def run(self):
        print("people is running...(do not extends Animal)")
def run_twice(animal):
    animal.run()
    animal.run()
    
run_twice(Cat())
run_twice(Animal())
run_twice(people())   #問題がなく実行できます。

Cat is running...
Cat is running...
Animal is running...
Animal is running...
people is running...(do not extends Animal)
people is running...(do not extends Animal)

3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?