Q:

Example of hierarchical inheritance in Python

belongs to collection: Python class & object programs

0

Hierarchical inheritance

When more than one derived classes are created from a single base – it is called hierarchical inheritance.

In this program, we have a parent (base) class name Details and two child (derived) classes named Employee and Doctor.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Python code to demonstrate example of hierarchical inheritance

# Python code to demonstrate example of 
# hierarchical inheritance

class Details:
    def __init__(self):
        self.__id="<No Id>"
        self.__name="<No Name>"
        self.__gender="<No Gender>"
    def setData(self,id,name,gender):
        self.__id=id
        self.__name=name
        self.__gender=gender
    def showData(self):
        print("Id: ",self.__id)
        print("Name: ", self.__name)
        print("Gender: ", self.__gender)

class Employee(Details): #Inheritance
    def __init__(self):
        self.__company="<No Company>"
        self.__dept="<No Dept>"
    def setEmployee(self,id,name,gender,comp,dept):
        self.setData(id,name,gender)
        self.__company=comp
        self.__dept=dept
    def showEmployee(self):
        self.showData()
        print("Company: ", self.__company)
        print("Department: ", self.__dept)

class Doctor(Details): #Inheritance
    def __init__(self):
        self.__hospital="<No Hospital>"
        self.__dept="<No Dept>"
    def setEmployee(self,id,name,gender,hos,dept):
        self.setData(id,name,gender)
        self.__hospital=hos
        self.__dept=dept
    def showEmployee(self):
        self.showData()
        print("Hospital: ", self.__hospital)
        print("Department: ", self.__dept)

def main():
    print("Employee Object")
    e=Employee()
    e.setEmployee(1,"Prem Sharma","Male","gmr","excavation")
    e.showEmployee()
    print("\nDoctor Object")
    d = Doctor()
    d.setEmployee(1, "pankaj", "male", "aiims", "eyes")
    d.showEmployee()

if __name__=="__main__":
    main()

Output

Employee Object
Id:  1
Name:  Prem Sharma
Gender:  Male  
Company:  gmr  
Department:  excavation 

Doctor Object  
Id:  1
Name:  pankaj  
Gender:  male  
Hospital:  aiims  
Department:  eyes

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python class & object programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Example of Hierarchical Inheritance in Python (2)... >>
<< Example of Multilevel Inheritance in Python (2)...