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()
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To