Examples of multi-state usage in Python Programming

Source: Internet
Author: User
This article mainly introduces the usage of polymorphism in Python programming, and analyzes the usage of polymorphism in Python in detail in the form of examples. For more information, see the following example to describe the usage of polymorphism in Python programming. Share it with you for your reference. The specific analysis is as follows:

What is polymorphism? As the name suggests, polymorphism means multiple manifestations. It is a mechanism, a capability, not a keyword. It is implemented in class inheritance and embodied in class method calls. Polymorphism means that variables do not know what the referenced object is. they behave differently based on the referenced object.

Let's take a look at a simple example, operator polymorphism:

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

We do not know the type of the two variables left and right of the + operator. when we give the int type, it performs addition. When the string type is given, it returns the result of concatenating two strings. That is, according to the different types of variables, the form is not feasible.

Let's look at an example. method polymorphism:

First, create a file named MyClass. py. the code is as follows:

_ Author __= 'mxi4oyu' classPeople: def say (self): print ("Hello everyone! ") ClassStudent: def say (self): print (" good teacher! ")

Create another Main. py file. the code is as follows:

_ Author __= 'mxi4oyu' fromrandom import choiceimportMyClassp1 = MyClass. people () stu1 = MyClass. student () # Using the choice method, we can randomly select an item in the list obj = choice ([p1, stu1]) print (type (obj) obj. say ()

The temporary Object obj we created is obtained by a random function. We do not know its specific type, but we can perform the same operation on it. That is, let it call the say method, and then it will behave differently according to its type. This is polymorphism.

I hope 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.