This file will demonstrate how inheritance allows child classes to adopt the methods and functionality available in its parent class and adding any additional functionality on top. This helps reduce the amount of duplicated code as it is bad practice to keep repeating yourself. According to the DRY acronym, "Do not repeat yourself."
devops_student [Parent/ Base Class]
- Attributes
- current_grade
private
- current_trainer
public
- current_grade
- Methods
- print_details
public
- change_current_grade
private
- print_details
student_data [Child/ Derived Class]
The student_data class has actually not got any unique methods of attributes, for the purpose of demonstrating inheritance, the child class has been left empty. This demonstrates how it can use all the attributes and methods in its parent class.
To inherit from a parent class, you simply put it in the brackets of a classes declaration:
super().__init__
is taking all the members of the parent class and giving the child class access.
class DevOpsStudent(StudentData):
def __init__(self, current_grade, current_trainer):
super().__init__(current_grade, current_trainer)
self.current_grade = current_grade
self.current_trainer = current_trainer
This is demonstrated in the parent classes file:
⚫ Here John is an instance of the DevOpsStudent class, it has taken two values that are assigned into the attributes it inherited from the parent class.
⚫ Secondly the parent classes method called print_details()
has been called in this class even though it has not been
created here, therefore it shows how inheritance is amazing when you want to allow classes to share attributes and methods.
John = DevOpsStudent(70, "Billy bog-man")
print(John.print_details())