Single and Multiple inheritance in Python
1. Single Inheritance
# Single Inheritance in Python with Student and Marks Details #-Base class class std_per_det: regno = input("Enter RegNo:") name = input("Enter Name:") course = input("Enter Course:") #Base class Method def show_std(self): print('Base Class value:',self.regno) print('Base Class value:',self.name) print('Base Class value:',self.course) #-Derived class class marks_det(std_per_det): p=int(input("Enter Physics Marks:")) c=int(input("Enter Chemistry Marks:")) m=int(input("Enter Maths Marks:")) b=int(input("Enter Biology Marks:")) tot=p+c+m+b avg=tot/4 #Derive class Method def show_marks(self): print('Physics:',self.p) print('Chemistry:',self.c) print('Maths:',self.m) print('Biology:',self.b) print('Total Marks:',self.tot) print('Average Marks:',self.avg) print("\nStudent Marks details") print("=================================") m=marks_det() # Object of Derive class m.show_std() # Access Base class method m.show_marks()
Output
2. Multiple Inheritance
# Multiple Inheritance - Inventory example #Base class - item_det class item_det: icode=input("Enter item code:") iname=input("Enter item Name:") def show_item_det(self): print("Item code:", self.icode) print("Item name:",self.iname) #Base class - bill_det class bill_det: qty=int(input("Enter Qty:")) price=int(input("Enter Price:")) tot=qty*price def show_bill_det(self): print("Item Qty:",self.qty) print("Item Price:",self.price) print("Total:",self.tot) #Child class invent_det Begins with inheriting Base classes item_det and bill_det class invent_det(item_det, bill_det): tax=bill_det.tot*18/100 bill_amt=bill_det.tot+tax def show_invent_det(self): print("TAX 18%:",self.tax) print("Total amount:",self.bill_amt) print("Inventory details") print("---------------------------------") i=invent_det() #Child class instance i.show_item_det() # invoking parent class item_det method i.show_bill_det() # invoking parent class bill_det method i.show_invent_det() #invoking own class method
Output