I. What is polymorphism?
Polymorphism relies on the inheritance and derivation of classes, which means that functions with different functions can use the same function names, so that functions with different contents can be called with a function name.
For a better understanding, take the Len () function to give an example:
The function of the Len () function is to find the length of a sequence, so how does the Len () function get to the length of the sequence?
The Len () function is to get the length of a sequence by executing the __len__ method of the object.
Some of the basic data types that are common in python, such as strings, dictionaries, lists, and tuples, have the name __len__ method, so the Len () function is out of order to know which class the object is generated from, as long as the __len__ method that calls them can get to the length of the sequence.
Let's manually simulate the function of the next Len function.
L1 = [All-in-one] # defines a list of examples through this list.
T1 = (+)
D1 = {' K1 ': ' v1 ', ' K2 ': ' V2 '}
L1.__LEN__ () # Let's start with the __len__ method of this object and see what it will do.
T1.__LEN__ ()
d1.__len__ () #l1,t1,d1 These three objects are not generated by a class at all, but they all have the same method, that is, the __len__, the length of which can be obtained by this method.
Output:
3 # Successfully obtained the length of this L1 object sequence. List
2 Length of #t1 (tuple)
2 Length of #d1 (list)
# Next, create a Test_len function that mimics the Len function to invoke the __len__ method of an object to get the length of a sequence.
def test_len (obj): # You can pass a parameter to the function, which has no restriction of any kind, and the value passed in can be any type
Print obj.__len__ () # The methods that call these objects are the same, but the results are different because the objects are generated by different classes.
Test_len (L1) # executes this function and L1 the object into it.
Output:
3 # Implements the same functionality as the Len function.
Test_len (T1)
Output:
2
Test_len (D1)
Output:
2
In fact, from the above example, it can be seen that the Python default is to support polymorphism ~
The benefits of this polymorphism are mainly two points:
Let the program become more flexible, regardless of the object to be transmitted to the function, the ever-changing, ultimately through a form to call ~
(Example: Len (L1))
Greatly increased the scalability of the program.
finally = = Quote my roommate's quote:
Polymorphism is standing in the definition of the point of view, polymorphism is to stand in the perspective of the use of ~
Polymorphism: The same invocation method is used to get different execution results.
Polymorphism: A variety of forms of things, such as humans, cats, dogs
This article is from the "Rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1917921
8.python Polygon Object Part.6 (polymorphism and polymorphism in Python class)