Inheritance

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Inheritance:

Ever heard of this dialogue from relatives “you look exactly like your
father/mother” the reason behind this is called ‘inheritance’. From the
Programming aspect, It generally means “inheriting or transfer of characteristics
from parent to child class without any modification”. The new class is called
the derived/child class and the one from which it is derived is called
a parent/base class.

What Is Inheritance?
The method of inheriting the properties of parent class into a child class is known
as inheritance. It is an OOP concept. Following are the benefits of inheritance.

1. Code reusability- we do not have to write the same code again and again,
we can just inherit the properties we need in a child class.
2. It represents a real-world relationship between parent class and child class.
3. It is transitive in nature. If a child class inherits properties from a parent
class, then all other sub-classes of the child class will also inherit the
properties of the parent class.

Sub-classing

Calling a constructor of the parent class by mentioning the parent class name in
the declaration of the child class is known as sub-classing. A child class identifies
its parent class by sub-classing.

__init__( ) Function
The __init__() function is called every time a class is being used to make an object.
When we add the __init__() function in a parent class, the child class will no longer
be able to inherit the parent class’s __init__() function. The child’s class __init__()
function overrides the parent class’s __init__() function.

Single Inheritance:

Single level inheritance enables a derived class to inherit characteristics from a


single parent class.

Example:

class employee1(): //This is a parent class

def __init__(self, name, age, salary):

self.name = name

self.age = age

self.salary = salary

class childemployee(employee1): //This is a child class

def __init__(self, name, age, salary,id):

self.name = name

self.age = age

self.salary = salary

self.id = id

emp1 = employee1('harshit',22,1000)

print(emp1.age)

Output: 22

Explanation:

• I am taking the parent class and created a constructor (__init__), class


itself is initializing the attributes with parameters (‘name’, ‘age’ and
‘salary’).
• Created a child class ‘childemployee’ which is inheriting the properties
from a parent class and finally instantiated objects ’emp1′ and ’emp2′
against the parameters.
• Finally, I have printed the age of emp1. Well, you can do a hell lot of things
like print the whole dictionary or name or salary

Multiple Inheritance:

Multiple level inheritance enables one derived class to inherit properties from
more than one base class.

Example:

class employee1(): //Parent class


def __init__(self, name, age, salary):
self.name = name
self. age = age
self.salary = salary
class employee2(): //Parent class
def __init__(self, name,age,salary,id):
self.name = name
self.age = age
self.salary = salary
self.id = id
class childemployee(employee1,employee2):
def __init__(self, name, age, salary,id):
self.name = name
self.age = age
self. salary = salary
self.id = id
emp1 = employee1('harshit',22,1000)
emp2 = employee2('arjun',23,2000,1234)
print(emp1.age)
print(emp2.id)

Output: 22,1234
Explanation:

In the above example, I have taken two parent class “employee1” and
“employee2”. And a child class “childemployee”, which is inheriting both parent
class by instantiating the objects ’emp1′ and ’emp2′ against the parameters of
parent classes.
Multilevel Inheritance:

Multi-level inheritance enables a derived class to inherit properties from an


immediate parent class which in turn inherits properties from his parent class.

Example:

class employee(): //Super class


def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary
class childemployee1(employee): //First child class
def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary

class childemployee2(childemployee1): //Second child class


def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
emp1 = employee('harshit',22,1000)
emp2 = childemployee1('arjun',23,2000)

print(emp1.age)
print(emp2.age)

Output: 22,23

Explanation:

• It is clearly explained in the code written above, Here I have defined the
superclass as employee and child class as childemployee1. Now,
childemployee1 acts as a parent for childemployee2.
• I have instantiated two objects ’emp1′ and ’emp2′ where I am passing the
parameters “name”, “age”, “salary” for emp1 from superclass “employee”
and “name”, “age, “salary” and “id” from the parent class “childemployee1”
Hybrid Inheritance
Hybrid inheritance involves multiple inheritance taking place in a single
program.
class Parent:
def func1(self):
print("this is function one")

class Child(Parent):
def func2(self):
print("this is function 2")

class Child1(Parent):
def func3(self):
print(" this is function 3"):

class Child3(Parent , Child1):


def func4(self):
print(" this is function 4")

ob = Child3()
ob.func1()

Python Super() Function


Super function allows us to call a method from the parent class.

class Parent:
def func1(self):
print("this is function 1")
class Child(Parent):
def func2(self):
Super().func1()
print("this is function 2")

ob = Child()
ob.func2()

Hierarchical Inheritance:
Hierarchical level inheritance enables more than one derived class to inherit
properties from a parent class.
class employee ():
def __init__(self, name, age, salary): //Hierarchical Inheritance
self.name = name
self.age = age
self.salary = salary

class childemployee1(employee):
def __init__(self,name,age,salary):
self.name = name
self.age = age
self.salary = salary

class childemployee2(employee):
def __init__(self, name, age, salary):
self.name = name
self.age = age
self. salary = salary
emp1 = employee('harshit',22,1000)
emp2 = employee('arjun',23,2000)

print(emp1.age)
print(emp2.age)

Output: 22,23

Explanation:

• In the above example, you can clearly see there are two child class
“childemployee1” and “childemployee2”. They are inheriting functionalities
from a common parent class that is “employee”.
• Objects ’emp1′ and ’emp2′ are instantiated against the parameters ‘name’,
‘age’, ‘salary’.
Compile-time Polymorphism:
A compile-time polymorphism also called as static polymorphism which gets
resolved during the compilation time of the program. One common example is
“method overloading”. Let me show you a quick example of the same.

class employee1():
def name(self):
print("Harshit is his name")
def salary(self):
print("3000 is his salary")

def age(self):
print("22 is his age")

class employee2():
def name(self):
print("Rahul is his name")

def salary(self):
print("4000 is his salary")

def age(self):
print("23 is his age")

def func(obj): //Method Overloading


obj.name()
obj.salary()
obj.age()

obj_emp1 = employee1()
obj_emp2 = employee2()

func(obj_emp1)
func(obj_emp2)
output:
Harshit is his name
3000 is his salary
22 is his age
Rahul is his name
4000 is his salary
23 is his age
Explanation:

• In the above Program, I have created two classes ’employee1′ and


’employee2′ and created functions for both ‘name’, ‘salary’ and ‘age’ and
printed the value of the same without taking it from the user.
• Now, welcome to the main part where I have created a function with ‘obj’
as the parameter and calling all the three functions i.e. ‘name’, ‘age’ and
‘salary’.
• Later, instantiated objects emp_1 and emp_2 against the two classes and
simply called the function . Such type is called method overloading which
allows a class to have more than one method under the same name.

Method Overloading in Python

Method overloading means creating multiple methods with the same name but
with different return types or parameters. Using method overloading, you can
perform different operations with the same function name by passing different
arguments.

Like other programming languages, method overloading is not supported in


python. If you try to overload a method in python, it won’t raise any compile-
time errors. Instead, it will consider using the last defined method. If you try to
call the overloaded methods with different arguments, you will get errors at
runtime.

Following is the example of creating a class with different methods with same
name but with different parameters in python.

class Addition:
def add(self, a, b):
print("a + b = {}".format(a + b))

def add(self, a, b, c):


print("a + b + c = {}".format(a + b + c))

c1 = Addition()
c1.add(10, 20, 30)
c1.add(10,20)
output:
ERROR!
a + b + c = 60
Traceback (most recent call last):
File "<string>", line 12, in <module>
TypeError: Addition.add() missing 1 required positional argument: 'c'

f you observe the above example, we created a class with two overloaded
methods, one with two parameters and another with three parameters. After that,
we created an object for Addition class and calling the add function by sending
different arguments.
Example 2:
class Addition:
# first sum for 2 params
def my_sum(self, a, b):
return a + b

# second overloaded sum for 3 params


def my_sum(self, a, b, c):
return a + b + c
obj = Addition()
print(obj.my_sum(3, 4))
print(obj.my_sum(3, 4, 5))

output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: my_sum() missing 1 required positional argument: 'c'

12

Method Overriding
Method Overriding

Method Overriding in Python is an OOPs concept closely related to inheritance. When a child
class method overrides(or, provides it's own implementation) the parent class method of the
same name, parameters and return type, it is known as method overriding.

In this case, the child class's method is called the overriding method and the parent class's
method is called the overriden method.

Method overriding is completely different from the concept of method overloading. Method
overloading occurs when there are two functions with the same name but different parameters.
And, method overloading is not directly supported in Python.

Parent class: The class being inherited is called the Parent or Superclass.

Child class : The class that inherits the properties and methods of the parent class is called the
Child or Subclass.

To override a method in Python, follow these steps:

1. Define a class that inherits from the parent class.


2. Declare a method in the subclass with the same name as the method in the
parent class that you want to override.
3. Provide the new implementation of the method in the subclass.

You can override a method in python. Look at the example below.

class Parent:
def func1(self):
print("this is parent function")

class Child(Parent):
def func1(self):
print("this is child function")

ob = Child()
ob.func1()

The functionality of the parent class method is changes by overriding the same method
in the child class.

You might also like