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.