AppDividend
Latest Code Tutorials

Python Inheritance Example | Inheritance In Python

0

Python Inheritance Example | Inheritance In Python is today’s topic. Inheritance allows us to define the class that inherits all the methods and properties of another class. The parent class is the class being inherited from, also called the base class. The child class is the class that inherits from another class, also called derived class.

Python Inheritance Example

Inheritance is a capability of one class to derive or inherit the properties from some other class. The benefits of inheritance are:

  1. It represents real-world relationships well.
  2. It provides reusability of code. We don’t have to write a same code again and again. It also allows us to add more features to the class without modifying it.
  3. It is transitive, which means that if the class B inherits from another class A, then all subclasses of B would automatically inherit from class A.

See the following code example.

# app.py

class Person(object):

    # Constructor
    def __init__(self, name):
        self.name = name

    # To get name
    def getName(self):
        return self.name

    # To check if this person is Student
    def isStudent(self):
        return True


# Inherited or Subclass (Note Person in bracket)
class Student(Person):

    # Here we return true
    def isStudent(self):
        return False


# Driver code
person = Person("Eleven")  # An Object of Person
print(person.getName(), person.isStudent())

student = Student("Krunal")  # An Object of Student
print(student.getName(), student.isStudent())

See the output.

➜  pyt python3 app.py
Eleven True
Krunal False
➜  pyt

Inheritance enables us to define the class that takes all the functionality from a parent class and allows us to add more.

Let’s breakdown the above code into pieces.

#Create a Parent Class In Python

Create a class named Person, with name as a property, and two methods getName(), isStudent().

class Person(object):

    # Constructor
    def __init__(self, name):
        self.name = name

    # To get name
    def getName(self):
        return self.name

    # To check if this person is Student
    def isStudent(self):
        return True

# Driver code
person = Person("Eleven")  # An Object of Person
print(person.getName(), person.isStudent())

#Create a Child Class

If we want to create the class that inherits the functionality from the another class, send the parent class as the parameter when creating the child class. See the following code.

class Student(Person):

    # Here we return true
    def isStudent(self):
        return False

Now a Student class has the same properties and methods as the Person class.

Use a Student class to create an object, and then execute the getName() and isStudent() methods.

student = Student("Krunal")  # An Object of Student
print(student.getName(), student.isStudent())

#Added the __init__() Function

We have already added the Constructor function inside the class Person.

def __init__(self, name):
        self.name = name

That means, at the time of the creation of the object, we can set the class properties.

When you add the __init__() function in the child class (in our case, it is Student class), the child class will no longer inherit the parent’s __init__() function.
The child’s __init__() function overrides the inheritance of the parent’s __init__() function.

If we want to keep the inheritance of the parent’s __init__() function, add a call to the parent’s __init__() function. See the following code.

class Student(Person):
  def __init__(self, name):
    Person.__init__(self, name)

#Different forms of Inheritance

#Single inheritance

When the child class inherits from only one parent class, it is called single inheritance. We saw an example above.

#Multiple inheritance

When the child class inherits from multiple parent classes, it is called multiple inheritance.
Unlike Java and like C++, Python supports multiple inheritances. We specify all parent classes as a comma-separated list in the bracket.

# app.py

class Base1(object):
    def __init__(self):
        self.str1 = "Eleven"
        print("First Base Class")


class Base2(object):
    def __init__(self):
        self.str2 = "Krunal"
        print("Second Base Class")


class Derived(Base1, Base2):
    def __init__(self):
        Base1.__init__(self)
        Base2.__init__(self)
        print("Derived Class")

    def printData(self):
        print(self.str1, self.str2)


obj = Derived()
obj.printData()

See the following output.

➜  pyt python3 app.py
First Base Class
Second Base Class
Derived Class
Eleven Krunal
➜  pyt

#Multilevel inheritance

Multilevel inheritance means GrandParent -> Parents -> Children kind of relationship.

class GrandParents(object):

    # Constructor
    def __init__(self, name):
        self.name = name

    # To get name
    def getName(self):
        return self.name


# Inherited or SubClass
class Parents(GrandParents):

    # Constructor
    def __init__(self, name, age):
        GrandParents.__init__(self, name)
        self.age = age

    # To get name
    def getAge(self):
        return self.age


# Inherited or SubClass
class Children(Parents):

    # Constructor
    def __init__(self, name, age, address):
        Parents.__init__(self, name, age)
        self.address = address

    # To get address
    def getAddress(self):
        return self.address


# Driver code
g = Children("Krunal", 360001, "Rajkot")
print(g.getName(), g.getAge(), g.getAddress())

See the output.

➜  pyt python3 app.py
Krunal 360001 Rajkot
➜  pyt

#Hierarchical inheritance

When more than one classes are derived from the single base class, such inheritance is known as the Hierarchical Inheritance, where features that are common in the lower level are included in the parent class.

Problems, where the hierarchy has to be maintained, can be solved efficiently using this inheritance.

In simple words, more than one derived classes are created from a single base.

#Hybrid inheritance

Hybrid inheritance is the combination of multiple inheritance and multilevel inheritance. The class is derived from the two classes as in the multiple inheritance. However, one of the parent classes is not the base class. It is a derived class. 

Hybrid Inheritance combines more than one form of inheritance. It is a blend of more than one type of inheritance.

Finally, Python Inheritance Example | Inheritance In Python is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.