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.