Python inheritance

Inheritance is one of the core concepts of object-oriented programming (OOP) languages. When new class created using existing class and newly created class obtain all the features or functionality automatically then this type of implementation called Inheritance.


Objectives

  • Try to understand inheritance feature conceptually

  • Python inheritance with example


Try to understand inheritance feature conceptually in Python

  • Parent class : Class which is going to extend by other class.

  • Child class : Class which is created using other class


Advantage of Inheritance
  • It provides the reusability of a code.

  • Save time and effort.

  • An inheritance leads to less development and maintenance costs. etc.


Python inheritance with example

Code

# Parent class
class Person:

    # Constructor
    def __init__(self, first_name, last_name, email=None):
        self.first_name = first_name
        self.last_name = last_name
        self.email = email

    def print_details(self):
        details = self.first_name + " " + self.last_name
        if self.email:
            details = " " + self.email
        print(details)

    def parent_method(self):
        print("Called Parent class method")


# Child class
class Customer(Person):

    # Child class method access parent property
    def print_email_address(self):
        print("Customer email is : " + self.email)

    # Called parent class method
    def called_parent_method(self):
        super().parent_method()


# Create Child class object
customer = Customer("Touhid", "Mia", "hmtmcse.com@gmail.com")

# Called parent class method from child object
customer.print_details()

# Called child class method
customer.print_email_address()

# Called child class method which access parent method
customer.called_parent_method()
Here
  • super() : It’s use for call parent class methods

  • Customer(Person) : By this first bracket and the class name use for inheritance in python.

  • customer.print_details() : Inheritance allow to call parent class method and property from child class


Python OOP Inheritance video tutorial