Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 23, 2020 12:52 am GMT

What is duck typing?

Duck Typing

The phrase originates from the saying: "If it walks like a duck, swims like a duck, quacks like a duck, then it probably is a duck." Cool saying, but what does this mean?

In practice, what this means is that as programmers, we can focus on the expected behaviour of an object. Even if a Person object isn't a Duck object, if a Person object has a "quack" method, it can quack. Simple as that.

class Duck:     def quack(self):         print("I can quack because I am a duck.") class Person:    def quack(self):         print("I can quack because it's defined.")# Attributes having the same behaviour suggest duck typingfor obj in Duck(), Person():     obj.fly() 
Enter fullscreen mode Exit fullscreen mode

In summary, duck typing focuses on an object's behaviour (method) - not type. It does not matter whether a person is actually a Duck or a Person. As long as I want that person to call the quack method and it can, we're good. That's why it is called duck typing: if it looks like a duck (e.g., it has a method called quack) then who cares if it's a duck or a person. As long as I can call the method I want to call on that object, I'm good.


Original Link: https://dev.to/icncsx/what-is-duck-typing-340n

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To