Python polymorphism and polymorphism

Source: Internet
Author: User

Referenced by: http://www.cnblogs.com/linhaifeng/articles/7340687.html

Polymorphism in Python refers to a class of things that have many forms. For example, animals have many forms, people, dogs, cats, and so on.

ImportABCclassAnimal (METACLASS=ABC. Abcmeta):#The same kind of things: animals@abc. AbstractmethoddefTalk (self):PassclassPeople (Animal):#one of the forms of animals: Man    defTalk (self):Print('Say hello')classDog (Animal):#Animal Form Two: the Dog    defTalk (self):Print('say Wangwang')classPig (Animal):#animal Form three: Pig    defTalk (self):Print('say Aoao')

Python polymorphism refers to the use of instances without regard to instance types, meaning that instances of different types have the same invocation method. For example, people, cats, dogs, etc. as long as the inheritance of animal can directly invoke its talk () method.

peo=people () dog=Dog () pig=Pig ()#peo, dog, pig are all animals, as long as the animal must have talk method  # So we don't have to think about what the specific type of the three are, but the direct use of Peo.talk () dog.talk () Pig.talk()# goes Further, We can define a unified interface to use def  func (obj):    obj.talk ()

Benefits of using polymorphism:

1. Increased flexibility of the program status quo, regardless of the ever-changing object, the user is the same form to invoke, such as func (animal)2. Increased program amount extensibility a new class was created by inheriting the animal class. The user does not need to change their own code, or with the Func (animal) to call

Python polymorphism and polymorphism

Related Article

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.