Inheritance in python ?

Inheritance
1. Inheritance is the person by which new feature are added to existing class or existing function.
2. No feature is remove.
3. The existing class is called base class and the new class is the derive class.
4. For inheriting any class use class_name.__init__(self,parameters of class)

ex:-  Person.__init__(self,name,age,address)

class Person:
this is base class of this program.
next class Employee inherit the all property of Person class.

class Person:
    def __init__(self,name,age,address):
        self.name=name
        self.age=age
        self.address=address
    def __str__(self):
        return "Name="+self.name + ", Age="+str(self.age) +", Address="+ self.address

class Employee:
this class inherit the property of base class Person
this class is base class for Manager class

class Employee(Person):
    def __init__(self,name,age,address,post,salary):
        Person.__init__(self,name,age,address)
        self.post=post
        self.salary=salary
    def __str__(self):
        return Person.__str__(self)+", Post="+self.post+", Salary="+str(self.salary)

class Manager:
this class is derived class of Employee
this class also have property of Person class

class Manager(Employee):
    def __init__(self,name,age,address,post,salary,department,secretry):
        Employee.__init__(self,name,age,address,post,salary)
        self.department=department
        self.secretry=secretry
    def __str__(self):
        return Employee.__str__(self)+"\nSecretry "+str(self.secretry)
class Person:
    def __init__(self,name,age,address):
        self.name=name
        self.age=age
        self.address=address
    def __str__(self):
        return "Name="+self.name + ", Age="+str(self.age) +", Address="+ self.address
class Employee(Person):
    def __init__(self,name,age,address,post,salary):
        Person.__init__(self,name,age,address)
        self.post=post
        self.salary=salary
    def __str__(self):
        return Person.__str__(self)+", Post="+self.post+", Salary="+str(self.salary)
class Manager(Employee):
    def __init__(self,name,age,address,post,salary,department,secretry):
        Employee.__init__(self,name,age,address,post,salary)
        self.department=department
        self.secretry=secretry
    def __str__(self):
        return Employee.__str__(self)+", Department="+self.department+"\nSecretry="+str(self.secretry)
print("Person Class")
p1=Person("Pappu",50,"delhi")
print(p1)
print("\nEmployee Class")
e1=Employee("pappu",50,"Delhi","President",1)
print(e1)
print("\nManager Class")
m1=Manager("pappu ",50," Delhi "," MD ",1," purchase",e1)
print(m1)

Output of above Program

Person Class
Name=Pappu, Age=50, Address=delhi

Employee Class
Name=pappu, Age=50, Address=Delhi, Post=President, Salary=1

Manager Class
Name=pappu , Age=50, Address= Delhi , Post= MD , Salary=1, Department= purchase
Secretry=Name=pappu, Age=50, Address=Delhi, Post=President, Salary=1

Leave a Reply