Regarding the three types of inheritance , overriding and polymorphism , inheritance is what we use most in daily use. When we need many similar subclasses, if we define them one by one, it will waste a lot of space and time. At this time, we only need to define a parent class, that is, define a template, and then inherit all the attributes and behaviors of the parent class. The factory is mass-producing a certain When making mechanical parts, it is not necessary to draw a drawing for each production, but to mass produce according to a drawing. We also adopt this idea when using inheritance in the program, but when we want to inherit a certain When certain changes are made to the accessories, we can use the rewriting method, while polymorphism combines inheritance and rewriting. Let's study it in turn.
The so-called inheritance means that the son inherits the father.
Let's learn about inheritance based on examples.
classBase:#Define a parent class named Base def__init__(self,name,age,id):self.name=nameself.age=ageself.id=idprint('Inherited the class Base')print('My name :',self.name)print('My age:',self.age)print('My student number:' ,self.id)defgoto_school(self):print(self.name,'Using the goto_school method in the Base class to go to school')classStudent(Base): #When inheriting the parent class, all methods in the parent class will be inherited passxiaoming= Student('Xiaoming',20,1001)xiaoming.goto_school()
The output is:
Inherited the Base class. My name: Xiao Ming. My age: 20. My student number: 1001. Xiao Ming is using the goto_school method in the Base class to go to school.
Let's analyze this example. First, we defined a class named Base above. This class provides us with a constructor method, including name, first name and student number, and then also provides a goto_school() method. Then we define a class named Student below, which inherits the above Base class, and then we directly call the Student class. Through the output results, we can see that even if there is nothing in the Student class, a series of operations can still be performed. These behaviors and attributes are inherited from Base, and then finally In one line, we also called the method in Base, and it can still be called successfully.