Inheritance
Written by Anish Ahuja (10/10/2020)
Introduction
In the previous lesson, we used classes to derive objects from them. In this lesson, we will apply this lesson further to create classes from classes. The parent class, or base class, is the class that is being inherited from. The class that is inherited is called the child class, or the derived class.
Creating a Child Class
So far, we have made a parent class. Now we can begin making the child class.
We use a pass command because we currently have nothing to add. Currently, we have made a Student class that has the same properties as the Person class.
The __init__ function
If we want to add our own unique properties, we need to use the __init__()
function:
If we add properties like so, we will override the parent class's properties. To preserve the parent class, we need to call the parent class's __init__()
function:
Now we can preserve the properties of the parent class, and we can begin to add our own properties to the child class.
The super() Function
There is also a super()
function, which can be used to inherit from the parent without using its direct name.
This does the same thing as Person.__init()
but allows for greater ease as it will inherit whatever the parent class is named.
Adding Properties to the Child Class
We can add new properties to the Student class. For example, here we will add the grade level of the student:
This will add a property to the student class, where all students are in the 11th grade. If we want to make a grade property that can be customized by each object, we need to add grade to the __init__()
function.
Finally, we can add methods to the child class:
Conclusion
In this lesson, we learned how to use inheritance on classes. We can inherit the properties of parent classes, add new properties, and create new properties. The concept of inheritance becomes more important as we get larger projects, as it organizes our code into classes and subclasses.
Last updated