"When you see a bird walking like a duck, swimming like a duck, or screaming like a duck, this bird can be called a duck ."
We do not care about the object type, whether it is a duck or not, but behavior.
For example, in Python, there are many file-like items, such as stringio, gzipfile, and socket. They have many identical methods. We use them as files.
Duck type is often used in dynamic languages and is very flexible, so that python does not want to create a lot of design patterns like Java.
The following example uses duck typing to implement polymorphism.
# Coding = utf-8class Duck: def quack (Self): Print "quaaaaaack! "Class bird: def quack (Self): Print" bird imitate duck. "Class Doge: def quack (Self): Print" Doge imitate duck. "def in_the_forest (duck): Duck. quack () Duck = duck () bird = bird () Doge = doge () for X in [duck, bird, Doge]: in_the_forest (X)
What is duck type (duck typing)