Regarding polymorphism, polymorphism is a combination of the above two methods. Through polymorphism, we can write a variety of programs.
Look at the picture below:
Polymorphism means that a method can be used in different ways in the parent class and subclass and can be called separately.
Look at the following example:
classBase:def__init__(self,name):self.name=nameprint('%s can read'%self.name)defreading(self):print('%s is reading a Chinese book'%self.name)classInherit_One(Base): defreading(self):print('%s Reading an English book'%self.name)classInherit_Two(Base):defreading(self):print('%s is reading a comic book'%self.name)a=Base('a')a.reading()b=Inherit_One ('b')b.reading()c=Inherit_Two('c')c.reading()
The output is:
a can read a is reading Chinese books b can read b is reading English books c can read c is reading comic books
It can be seen that each inheritor overrides the reading method, and then when we call this method, we call it through different classes. This method can help us define different methods with the same name in different classes, which seems confusing. However, the various management systems in our reality are often inseparable from the use of polymorphism.
After studying these sections, everyone must have realized the methods of inheritance and rewriting. Regarding polymorphism, you need to practice and master it in practical problems. Object-oriented sounds more abstract, but it is not too difficult to master.