What is the difference between polymorphism and duck typing?

后端 未结 4 1471
心在旅途
心在旅途 2020-12-12 16:10

I\'m a little confused with the two terms, here\'s what I know:

Polymorphism is the ability of object of different types to be handled by a common interface. While d

4条回答
  •  甜味超标
    2020-12-12 16:37

    This is an example for Polymorphism in Python.

    class Animal:
        def __init__(self, name):    # Constructor of the class
            self.name = name
        def talk(self):              # Abstract method, defined by convention only
            raise NotImplementedError("Subclass must implement abstract method")
    
    class Cat(Animal):
        def talk(self):
            return 'Meow!'
    
    class Dog(Animal):
        def talk(self):
            return 'Woof! Woof!'
    
    animals = [Cat('Missy'),
               Cat('Mr. Mistoffelees'),
               Dog('Lassie')]
    
    for animal in animals:
        print animal
        print animal.name + ': ' + animal.talk()
    

    This is an example for duck Typing in Python.

    class Duck:
        def quack(self):
            print("Quaaaaaack!")
        def feathers(self):
            print("The duck has white and gray feathers.")
        def name(self):
            print("ITS A DUCK NO NAME")
    
    
    class Person:
        def quack(self):
            print("The person imitates a duck.")
        def feathers(self):
            print("The person takes a feather from the ground and shows it.")
        def name(self):
            print("John Smith")
    
    def in_the_forest(duck):
        duck.quack()
        duck.feathers()
        duck.name()
    
    def game():
        for element in [ Duck() , Person()]:
            in_the_forest(element)
    
    game()
    
    • In polymorphism we see subclass (Cat and Dog) inheriting from the parent class (Animal) and overriding the method Talk.
    • In case of duck typing we don’t create a subclass instead new class is created with method having same name but different function.

提交回复
热议问题