Skip to content

Inheritance

Defining new class from the existing class is known as Inheritance.
After inheritance, old class is called as base or super or parent class and newly created class is called as derived or sub or child class.
 
defining sub class:
class <subClassName>(<ParentClassName>):
members of child class
🐍
filename.py
#Example Program:
class A:
    x=0
    y=0

class B(A):#deriving B class from Class A
    a=0
    b=0

objA=A() #declaration of A class object
objA.x=12
objA.y=24
print(objA.x)
print(objA.y)

objB=B() #declaration of A class object
objB.a=13
objB.b=36
objB.x=90
print(objB.x)
print(objB.a)
print(objB.b)

Types of Inheritances:
1. Single or Single Level
2. Multi Level
3. Hierarchical
4. Multiple
5. Hybrid

🐍
filename.py
#Example of Multi Level Inheritance
class Person:
     name="none"
     age=0
     
     def ShowPer(self):
        print("Name :",self.name)
        print("Age:",self.age)
        return

class Husband(Person):
    wife="none"
       
    def ShowHus(self):
        print("Wife:",self.wife)
        return

class Father(Husband):
    childName="none"
    
    def showFat(self):
        print("Child Name:",self.childName)
        return

#main program
obj=Father()

obj.ShowPer()
obj.ShowHus()
obj.showFat()
🐍
filename.py
#Example of Hierarichal Inheritance
class Person:
     name="none"
     age=0
     
     def ShowPer(self):
        print("Name :",self.name)
        print("Age:",self.age)
        return

class Husband(Person):
    wife="none"
       
    def ShowHus(self):
        print("Wife:",self.wife)
        return

class Employee(Person):
    desg="none"
    sal=0
    
    def ShowEmp(self):
        print("Designation:",self.desg)
        print("Salary:",self.sal)
        return

#main program
obj1=Husband()
obj2=Employee()

obj1.ShowPer()
obj1.ShowHus()

obj2.ShowPer()
obj2.ShowEmp()
🐍
filename.py
#Example of Multiple Inheritance
class Father:
     FatName="none"
          
     def ShowFat(self):
        print("Father Name :",self.FatName)
        return

class Mother:
    MotName="none"
       
    def ShowMot(self):
        print("Mother Name:",self.MotName)
        return

class Son(Father,Mother):
    SonName="none"
        
    def ShowSon(self):
        print("Son Name:",self.SonName)
        return

#main program
obj=Son()

obj.ShowFat()
obj.ShowMot()
obj.ShowSon()
🐍
filename.py
#Example of Hybrid Inheritance
class Marriage:
    dom="none"
    
    def ShowMar(self):
        print("Marraige Date:",self.dom)
        return


class Father(Marriage):
     FatName="none"
          
     def ShowFat(self):
        print("Father Name :",self.FatName)
        return

class Mother(Marriage):
    MotName="none"
       
    def ShowMot(self):
        print("Mother Name:",self.MotName)
        return

class Son(Father,Mother):
    SonName="none"
        
    def ShowSon(self):
        print("Son Name:",self.SonName)
        return

#main program
obj=Son()

obj.ShowFat()
obj.ShowMot()
obj.ShowSon()