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.