Understand Python's duck typing

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

Not limited to Python, programming has the concept of polymorphism. This is one of the concepts of object-oriented programming, and in Japanese it is called polymorphism and diversity.

If there are methods with the same name, even if the class types are different, you can use them, and you can switch between the same operations on different objects.

Such code is called 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():           #Please note, not a subclass of 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())   #It can be executed without any problem.

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)

Recommended Posts

Understand Python's duck typing
A way to understand Python duck typing
Python ABC-Abstract Classes and Duck Typing