Py14: Inheritance

Inheritance is deriving a new class from an existing class. Derived class or child class inherits attributes and methods from Base class or also known as Parent class.

Declare Inheritance

Inheritance is declared by specifying the base class in side a parentheses that comes after the derived class.

class DerivedCLass(BaseClass):
    # statement

Example, Person is the base class and Student is the derived class.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def displayPerson(self):
        print("Name " , self.name , " Age " , self.age)

class Student(Person):
    pass


stud = Student("Rajini",70)
stud.displayPerson()

Output

Name  Rajini  Age  70

Child class constructor

When child class defines its own constructor, it will no longer inherits it's parent's __init__ function. To maintain the inheritance, the child class has to call it's parent's constructor and initializes the attributes.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def displayPerson(self):
        print("Name " , self.name , " Age " , self.age)

class Student(Person):
    def __init__(self, name, age, cgpa):
        super().__init__(name, age)
        self.cgpa = cgpa
    def displayStudent(self):
        print("Name :" , self.name , " Age :" , self.age, " CGPA :", self.cgpa)

Output

stud = Student("Rajini",70, 3.87) stud.displayStudent()
Name : Rajini  Age : 70  CGPA : 3.87

the super() function allows child class to access methods of its parent class.

Method Overriding

When child class has a method with same name as the method of its parent class, the method in the parent class will be overridden.

class Animal:
    def describe(self):
        print("I am an animal")

class Bird:
    def describe(self):
        print("I am a bird")


animal = Bird()
animal.describe()

Output

I am a bird

Types of Inheritance

Single, multilevel inheritance, multiple and hierarchical inheritance. We already seen single inheritance. In hierarchical inheritance a parent class has more than one child class.

class A:
    pass
class B(A):
    pass
class C(A):
    pass

Next, the multilevel inheritance. More than one derived class is specified from a parent class. The derived class in turn becomes the base class for another derived class an so on.

class A:
    pass
class B(A):
    pass
class C(B):
    pass

and finally, the multiple inheritance. A child class may have more than one parent, and in Python we can do that by specifying parent classes separated by comma.

class A:
    pass
class B:
    pass
class C(A, B):
    pass

Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net