Breaking News: Grepper is joining You.com. Read the official announcement!
Check it out

Implementing duck typing#

Sumit Rawal answered on May 17, 2023 Popularity 3/10 Helpfulness 1/10

Contents


More Related Answers

  • duck typing in python
  • duck typing in python
  • duck typing in python
  • duck typing in python

  • Implementing duck typing#

    0

    Let us see an example to implement thisExplanation

    In line 13, the type of animal is not defined in the definition of the method Sound.

    Type of animal is determined when the method is called, so it does not matter which object type you are passing as a parameter in the Sound() method, what matters is that the Speak() method should be defined in all the classes whose objects are passed in the Sound() method.

    We can use any property or method of animal in the AnimalSound class as long as it is declared in that class.

    Conclusion

    Now coming back to why it is called Duck typing: So, if a bird speaks like a duck, swims like a duck, and eats like a duck, that bird is a duck.

    Similarly, in the above example, the animal object does not matter in the definition of the Sound method as long as it has the associated behavior, Speak(), defined in the object’s class definition. In layman terms, since both the animals, dog and cats, can speak like animals, they both are animals. This is how we have achieved polymorphism without inheritance.:

    Popularity 3/10 Helpfulness 1/10 Language python
    Source: Grepper
    Tags: python
    Link to this answer
    Share Copy Link
    Contributed on May 17 2023
    Sumit Rawal
    0 Answers  Avg Quality 2/10

    Closely Related Answers



    1

    We say that if an object quacks like a duck, swims like a duck, eats like a duck or in short, acts like a duck, that object is a duck.

    Popularity 9/10 Helpfulness 3/10 Language whatever
    Source: Grepper
    Link to this answer
    Share Copy Link
    Contributed on May 17 2023
    Sumit Rawal
    0 Answers  Avg Quality 2/10


    X

    Continue with Google

    By continuing, I agree that I have read and agree to Greppers's Terms of Service and Privacy Policy.
    X
    Grepper Account Login Required

    Oops, You will need to install Grepper and log-in to perform this action.