A multi-state usage example of Python programming

Source: Internet
Author: User
The examples in this paper describe the polymorphic usage of Python programming. Share to everyone for your reference. The specific analysis is as follows:

What is polymorphic? As the name implies, polymorphism is the meaning of many forms of expression. It is a mechanism, a capability, not a keyword. It is implemented in the class's inheritance and is reflected in the method invocation of the class. Polymorphism means that a variable does not know what the referenced object is, and behaves differently depending on how the object is referenced.

Let's look at a simple example of operator polymorphism:

A=34b=57print (a+b) a= "World" b= "Hello" print (a+b)

We don't know what the two variables of the + operator are, and when we give the int type, it does the addition operation. When we give a string type, it returns the result of a concatenation of two strings. That is, according to the different types of variables, the performance of the form.

Let's look at one more example, method polymorphism:

Let's start by creating a file named Myclass.py, with the following code

__author__= ' Mxi4oyu ' classpeople:  def Say (self):    print ("Hello everyone! ") Classstudent:  def Say (self):    print (" Good teacher! ")

Let's create a main.py file with the following code:

__author__= ' Mxi4oyu ' fromrandom import choiceimportmyclassp1=myclass.people () stu1=myclass.student () # With the choice method we can randomly select an item in the list Obj=choice ([P1,STU1]) print (type (obj)) Obj.say ()

The temporary object we created, obj, is taken out by a random function, and we don't know its specific type, but we can do the same thing for it. That is, let it call the Say method, and then it behaves differently depending on its type. This is polymorphism.

Hopefully this article will help you with Python programming.

  • 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.