What is duck type (duck typing)

Source: Internet
Author: User

"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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.