Python Working With Inheritance - Oops

Python Working With Inheritance - Oops

Inheritance in python defined as acquiring the properties from the parent/base class to its child classes. In reality we develop complex applications that provides more utilities to users. In developer perspective each utility involves different modules which work together to provide an utility to the user. Each module involves many functions and classes. Most of the these shares similar properties and functionalities. If did not use inheritance concept then we have to write the same code in different functions or classes which results in writing more code and it will become difficult to maintain the code. It will also take more time to fix bugs or to enhance the existing functionality.

Advantage of the inheritance is that we write a base class and implement the common functionalities init and inherit it in a child class. Now, the child class gets all the properties from the base class. we can use that functionality and we can also implement extra functionality. We can also override the base class functionality if it requires.

Python Inheritance Example

class Person(object):

    def __init__(self, first_name, last_name, age, gender):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        self.gender = gender

    def print_full_name(self):
        msg = '{first_name} {last_name}'.format(
            first_name=self.first_name, last_name=self.last_name)

class Teacher(Person):

    def __init__(self, first_name, last_name, age, gender, subject):
        super().__init__(first_name, last_name, age, gender)
        self.subject = subject

    def print_subject(self):
        msg = "Subject: {subject}".format(subject=self.subject)

class Student(Person):

    def __init__(self, first_name, last_name, age, gender, std_class):
        super().__init__(first_name, last_name, age, gender)
        self.std_class = std_class

    def print_class_name(self):
        msg = 'Class name: {name}'.format(name=self.std_class)

p = Person('Shera', 'Md', 20, 'Male')

t = Teacher('Gilchrist', 'Adam', 20, 'Male', 'Maths')

s = Student('Priya', 'Ch', 20, 'Female', '3rd Class')

In the above example we have created a base class "Person" and implemented the common functionality and we inherited it in its base classes "Teacher" and "Student". We also implemented the exta functionalities in child classes in addition to inherited functionality.