Examples of multi-state usage in Python programming

Source: Internet
Author: User

This example describes the polymorphic usage of Python programming. Share to everyone for your reference. The specific analysis is as follows:

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

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

?

1 2 3 4 5 6 a=34 b=57 Print (a+b) a= "The World" b= "Hello" print (a+b)

We don't know what kind of two variables the + method operator is, and when we give the int type, it does the addition. 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, performance can not form.

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

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

?

1 2 3 4 5 6 7 __author__= ' Mxi4oyu ' classpeople:def Say (self): print ("Hello everyone!") Classstudent:def Say (self): print ("Good teacher!") ")

We'll create a main.py file with the following code:

?

1 2 3 4 5 6 7 8 9 __author__= ' Mxi4oyu ' fromrandom import choice Importmyclass p1=myclass.people () stu1=myclass.student () # By choice method We can randomly select one item in the list Obj=choice ([P1,STU1]) print (type (obj)) Obj.say ()

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

I hope this article will help you with your Python programming.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.