In this Python oops program, we will create a class to show inheritance in Python with example. This code demonstrates the concept of inheritance
Inheritance in Python
Steps to solve the program
- The Person class has a constructor method __init__ that takes two parameters, name and age. Inside the constructor, the values of name and age are assigned to the instance variables self.name and self.age, respectively. This class also defines a method print_details that prints the name and age of the person.
- The Student class is a subclass of Person, as indicated by (Person) in its class definition. It adds two additional attributes, student_id and grades, which represent the student’s ID and grades, respectively. The class overrides the print_details method inherited from Person and extends it by calling the print_details method of the superclass using super().print_details(), and then printing the student ID.
- An object of the Student class is created with the name “Jade Smith”, age 24, student ID “A12345”, and grades [‘A’, ‘A+’]. The student variable now refers to this object.
- The print_details method is then called on the student object, which executes the overridden print_details method in the Student class. This method first calls the print_details method of the Person class using super().print_details() to print the person’s name and age, and then prints the student ID.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def print_details(self):
print("Name:", self.name)
print("Age:", self.age)
class Student(Person):
def __init__(self, name, age, student_id, grades):
super().__init__(name, age)
self.student_id = student_id
self.grades = grades
def print_details(self):
super().print_details()
print("Student ID:", self.student_id)
# Create an object of the Student class
student = Student("Jade Smith", 24, "A12345", ['A','A+'])
student.print_details()
Output:
Name: Jade Smith
Age: 24
Student ID: A12345
Related Articles
Create a Python class called Cat that inherits from the Animal class.
Create a Python class called BankAccount with attributes account_number and balance.
Create a Python class called SavingsAccount that inherits from the BankAccount class.
Create a Python class called CheckingAccount that inherits from the BankAccount class.
Create a Python class called Car with attributes make, model, and year.
Create a Python class called ElectricCar that inherits from the Car class.