Write a program to single inheritance in Python
This Python program demonstrates inheritance in object-oriented programming. It defines two classes, Details and Student, where the Student class inherits from the Details class. Here's an explanation of the program:
- class Details:: This is the Details class, which serves as the parent class.
- __init__(self): The constructor method initializes three instance variables: name, total, and per. All are initially set to 0 or an empty string.
- setData(self, name, total, per): This method allows you to set values for the name, total, and per instance variables.
- showData(self): This method prints the values of name, total, and per.
- class Student(Details):: The Student class is a child class that inherits from the Details class. This means it inherits the attributes and methods of the parent class.
- __init__(self): The constructor method of the Student class initializes an additional instance variable, Grade, which is initially set to an empty string.
- setStudent(self, name, total, per, grade): This method allows you to set values for name, total, per, and the new grade instance variable. It calls the setData method from the parent class to set the common attributes.
- showStudent(self): This method first calls the showData method from the parent class to display the details inherited from Details. It then prints the grade attribute.
- e = Student(): An instance of the Student class is created and assigned to the variable e.
- e.setStudent("Kim", 430, 86.00, 'B') : The setStudent method is called on the e object to set the student's details, including the name, total, percentage, and grade.
- e.showStudent(): The showStudent method is called to display the student's details, including the name, total, percentage, and grade.
When you run the program, it creates an instance of the Student class, sets the student's details using the setStudent method, and then displays these details using the showStudent method. This program showcases the concept of inheritance, where the Student class inherits attributes and methods from the Details class and extends them with its own attributes and methods.
Source Code
class Details:
def __init__(self):
self.name = ""
self.total = 0
self.per = 0
def setData(self,name,total,per):
self.name = name
self.total = total
self.per = per
def showData(self):
print("Name :", self.name)
print("Total :", self.total)
print("Percentage :", self.per)
class Student(Details): #Inheritance
def __init__(self):
self.Grade = ""
def setStudent(self,name,total,per,grade):
self.setData(name,total,per)
self.grade = grade
def showStudent(self):
self.showData()
print("Grade :", self.grade)
e=Student()
e.setStudent("Kim",430,86.00,'B')
e.showStudent()
Output
Name : Kim
Total : 430
Percentage : 86.0
Grade : B