Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
UNIT -5::PP
======================================================================
Inheritance: Introduction, inheriting classes, types of inheritance,overridingmethods,abstract
classes and interfaces
...
Inheritance provides code
reusability to the program because we can use an existing class to create a new class instead of
creating it from scratch
...
A child class can also provide its specific implementation to the
functions of the parent class
...
Consider the following syntax to inherit a base class into the derived class
...
Parent class is the class being inherited from, also called base class
...
Syntax
class derived-class(base class):
A class can inherit multiple classes by mentioning all of them inside the bracket
...
Syntax
class derive-class(
...
firstname = fname
self
...
firstname, self
...
printname()
Example
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d
...
speak()
Output:
dog barking
Animal Speaking
Add the __init__() Function
So far we have created a child class that inherits the properties and methods from its parent
...
Note: The __init__() function is called automatically every time the class is being used to create a
new object
...
When you add the __init__() function, the child class will no longer inherit the
parent's __init__() function
...
To keep the inheritance of the parent's __init__() function, add a call to the
parent's __init__() function:
Example
class Person:
def __init__(self, fname, lname):
self
...
lastname = lname
def printname(self):
print(self
...
lastname)
class Student(Person):
def __init__(self, age,fname, lname):
Person
...
age=age
Mike Olsen
age: 20
x = Student(20,"Mike", "Olsen")
x
...
age)
Now we have successfully added the __init__() function, and kept the inheritance of the parent
class, and we are ready to add functionality in the __init__() function
...
firstname = fname
self
...
firstname, self
...
__init__(fname, lname)
x = Student("Mike", "Olsen")
x
...
firstname = fname
self
...
firstname, self
...
__init__(fname, lname)
self
...
graduationyear)
In the example below, the year 2019 should be a variable, and passed into the Student class when
creating student objects
...
firstname = fname
self
...
firstname, self
...
__init__(fname, lname)
self
...
graduationyear)
Add Methods
Example
Add a method called welcome to the Student class:
class Person:
def __init__(self, fname, lname):
self
...
lastname = lname
Welcome Mike Olsen to the class of
2019
def printname(self):
print(self
...
lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super()
...
graduationyear = year
def welcome(self):
print("Welcome", self
...
lastname, "to the
class of", self
...
welcome()
==============================================================================
super() in Python IN Single inheritance & Multiple inheritances
The super() function in Python makes class inheritance more manageable and extensible
...
The super() function has two major use cases:
To avoid the usage of the super (parent) class explicitly
...
Single inheritance
Consider the example below, where the parent class is referred to by the super keyword:
class Computer():
def __init__(self, computer, ram, storage):
self
...
ram = ram
The mobile is: Apple
The RAM is: 2
The storage is: 64
The model is: iPhone X
self
...
__init__(computer, ram, storage)
self
...
computer)
print('The RAM is:', Apple
...
storage)
print('The model is:', Apple
...
The usage of the super keyword in line 10 allows the child class to access the parent
class’s init() property
...
Multiple inheritances
The following example shows how the Super() function is used to implement multiple
inheritances:
class Animal:
I am a cat
...
print(animalName, 'is an animal
...
Cat is a mammal
...
class Mammal(Animal):
def __init__(self, mammalName):
Bat cannot swim
...
')
Bat is a mammal
...
__init__(mammalName)
Bat is an animal
...
")
super()
...
")
super()
...
');
super()
...
The Cat class is called first
...
The CannotSwim parent class is called since it appears before CannotFly in the order
of inheritance; this follows Python’s Method Resolution Order (MRO) which outlines
the order in which methods are inherited
...
The CannotFly class is called
...
The Mammal class is called
...
Finally, the Animal class is called
...
Bats are flying mammals, but they cannot swim, which is why
it is instantiated with the CannotSwim class
...
The Mammal class then invokes
the Animal class’s constructor
========================================================================
Types of inheritance Python
Inheritance is defined as the capability of one class to derive or inherit the properties from some
other class and use it whenever needed
...
It provides reusability of code
...
Also, it
allows us to add more features to a class without modifying it
...
Types of Inheritance in Python
Types of Inheritance depends upon the number of child and parent classes involved
...
Single Inheritance:
2
...
Multilevel Inheritance
4
...
# Python program to demonstrate
# single inheritance
# Base class
class Parent:
def func1(self):
print("This function is in parent class
...
")
Output:
This function is in parent class
...
# Driver's code
object = Child()
object
...
func2()
Multiple Inheritance: When a class can be derived from more than one base class this type of
inheritance is called multiple inheritance
...
Syntax:
class A:
# variable of class A
# functions of class A
class B:
# variable of class A
# functions of class A
class C(A, B):
# class C inheriting property of both class A and B
# add more properties to class C
As you can see, instead of mentioning one class name in parentheses along with the child class, we
have mentioned two class names, separated by comma ,
...
Therefore, the syntax should actually be:
class A(A1, A2, A3,
...
# You can add properties to A class too
Example:
# Python program to demonstrate
# multiple inheritance
# Base class1
class Mother:
mothername = ""
def mother(self):
print(self
...
fathername)
# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", self
...
mothername)
1
...
3
...
5
...
7
...
9
...
11
...
13
...
fathername = "RAM"
s1
...
parents()
Example
class Calculation1:
def Summation(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d
...
Multiplication(10,20))
print(d
...
5
Constructors in multiple inheritance
class hi:
def __init__(self,b):
self
...
b)
class hi1:
def __init__(self,c):
self
...
a=a
hi
...
__init__(self,c)
def disp(self):
#super()
...
a,self
...
c)
k=hi2(10,20,30)
k
...
This is similar to a relationship representing a child
and grandfather
...
grandfathername = grandfathername
# Intermediate class
class Father(Grandfather):
def __init__(self, fathername, grandfathername):
self
...
__init__(self, grandfathername)
# Derived class
class Son(Father):
def __init__(self,sonname, fathername, grandfathername):
self
...
__init__(self, fathername, grandfathername)
def print_name(self):
print('Grandfather name :', self
...
fathername)
print("Son name :", self
...
grandfathername)
s1
...
class Animal:
2
...
print("Animal Speaking")
4
...
#The child class Dog inherits the base class Animal
6
...
def bark(self):
8
...
10
...
class DogChild(Dog):
12
...
print("Eating bread
...
d = DogChild()
15
...
bark()
16
...
speak()
17
...
eat()
Example:
class hi:
def __init__(self,b):
self
...
b)
class hi1(hi):
def __init__(self,b,c):
self
...
__init__(self,b)
class hi2(hi1):
def __init__(self,a,b,c):
self
...
__init__(self,b,c)
def disp(self):
#super()
...
a,self
...
c)
k=hi2(10,20,30)
Hi-1 10 20 30
Output:
dog barking
Animal Speaking
Eating bread
...
disp()
Hierarchical Inheritance: When more than one derived classes are created from a single
base this type of inheritance is called hierarchical inheritance
...
Example:
# Python program to demonstrate
Output:
# Hierarchical inheritance
This function is in parent class
...
class Parent:
def func1(self):
This function is in parent class
...
")
This function is in child 2
...
")
# Derivied class2
class Child2(Parent):
def func3(self):
print("This function is in child 2
...
func1()
object1
...
func1()
object2
...
Example:
# Python program to demonstrate
Output:
# hybrid inheritance
This function is in school
...
def func1(self):
print("This function is in school
...
")
class Student2(School):
def func3(self):
print("This function is in student 2
...
")
# Driver's code
object = Student3()
object
...
func2()
====================================================================
Multipath Inheritance
When a class is derived from two or more classes which are derived from the same base class then
such type of inheritance is called multipath inheritance
...
===============================================================
The issubclass(sub,sup) method
The issubclass(sub, sup) method is used to check the relationships between the specified
classes
...
Example
Output:
1
...
def Summation(self,a,b):
False
3
...
class Calculation2:
5
...
def Multiplication(self,a,b):
return a*b;
7
...
9
...
d = Derived()
11
...
print(issubclass(Calculation1,Calculation2))
The isinstance (obj, class) method
The isinstance() method is used to check the relationship between the objects and classes
...
e
...
e
...
Example
1
...
True
3
...
class Calculation2:
5
...
def Multiplication(self,a,b):
return a*b;
7
...
9
...
d = Derived()
11
...
When the parent class method is defined in the child class with some specific
implementation, then the concept is called method overriding
...
Consider the following example to perform method overriding in python
...
class Animal:
2
...
def speak(self):
print("speaking")
4
...
6
...
d = Dog()
d
...
class Bank:
Output:
2
...
return 10;
Bank Rate of interest: 10
SBI Rate of interest: 7
ICICI Rate of interest: 8
4
...
def getroi(self):
6
...
8
...
def getroi(self):
10
...
b1 = Bank()
12
...
b3 = ICICI()
14
...
getroi());
15
...
getroi());
16
...
getroi());
=======================================================================
Data abstraction in python
Abstraction is an important aspect of object-oriented programming
...
After this, the attribute will not be visible outside of the class through
the object
...
class Employee:
Output:
2
...
def __init__(self):
The number of employees
2
AttributeError: 'Employee'
object has no attribute
'__count'
4
...
Employee
...
__count+1
def display(self):
6
...
__count)
7
...
emp2 = Employee()
9
...
print(emp
...
finally:
12
...
display()
===========================================================================
Abstract Method in python
An Abstract method is a method which is declared but does not have implementation such
type of methods are called as abstract methods
...
This abstract method is present in the abc module in python, and hence, while declaring the
abstract method, we have to import the abc module compulsory
...
Here the Child class is responsible for providing an implementation for the parent class
abstract method
...
Example:
from abc import ABC, abstractmethod
class Vehicle(ABC):
@abstractmethod
def getNoOfWheels(Self):
pass
The child classes are responsible to provide implementation to parent class abstract
methods
...
These classes are called concrete
classes
...
from abc import ABC, abstractmethod
class Vehicle(ABC): ##abstarct class
@abstractmethod ##abstract method
def getNoOfWheels(Self):
pass
class Bus(Vehicle): ##implementing parent abstract class by using child class
def getNoOfWheels(self):
return 6
class Auto(Vehicle): ##implementing parent abstract class by using child class
def getNoOfWheels(self):
return 3
b=Bus()
print(b
...
getNoOfWheels())
The output is:
============================================================
What is the advantage of declaring an abstract method in the parent class
Ans: By declaring an abstract method in the child class, we can provide some guidelines to
the child classes, such that they should compulsorily implement those methods; otherwise,
child class will take it as optional
...
from abc import ABC, abstractmethod
class Vehicle(ABC):
def getNoOfWheels(Self):
pass
class Bus(Vehicle):
pass
b=Bus()
The output is: It is not giving any output, but it is not giving any error
...
If a class containing one abstract method and if we are extending ABC class then
instantiation id not possible;
for Abstract class with an abstract method instantiation(creating an object) is not possible
...
An abstract class can contain a zero number of abstract methods
from abc import *
class Test(ABC):
pass
t=Test()
===============================
But, the following example contains an abstract method and does not include an abstract
class, and hence we can perform instantiation
...
If we are creating a child class for abstract class, then for every abstract method of parent
class compulsory we should provide an implementation in the child class; otherwise child
class also becomes an abstract class, and we cannot create an object for the child class
...
from abc import *
class Test(ABC):
@abstractmethod
def m1(self):
pass
class SubTest(Test):
pass
s=SubTest()
##The output:
File "C:/Users/User/
...
py", line 10, in
s=SubTest()
TypeError: Can't instantiate abstract class SubTest with abstract methods m1
The following example contains an abstract class with two abstract methods when we
create a child class, we are implementing only one abstract method of the parent class, and
hence, we cannot perform instantiation
...
# Python program showing
Output:
# implementation of abstract
# class through subclassing
True
True
import abc
class parent:
def geeks(self):
pass
class child(parent):
def geeks(self):
print("child class")
# Driver code
print( issubclass(child, parent))
print( isinstance(child(), parent))
k1=parent()
k2=child()
Example-4
Concrete Methods in Abstract Base Classes :
Concrete classes contain only concrete (normal)methods whereas abstract classes may contain
both concrete methods and abstract methods
...
Let look over the example to invoke the method using super():
# Python program invoking a
utput:
# method using super()
Abstract Base Class
import abc
subclass
from abc import ABC, abstractmethod
In the above program, we can invoke the
methods in abstract classes by using super()
...
rk()
print("subclass ")
# Driver code
r = K()
r
...
If python allows
creating an object for abstract classes then using that object if anyone calls the abstract method,
but there is no actual implementation to invoke
...
Due to the fact, an
abstract class is not a concrete class, it cannot be instantiated
...
# Python program showing
# abstract class cannot
# be an instantiation
from abc import ABC,abstractmethod
class Animal(ABC):
@abstractmethod
def move(self):
pass
class Human(Animal):
def move(self):
print("I can walk and run")
Output:
Traceback (most recent call last):
File
"/home/ffe4267d930f204512b7f501bb1bc489
...
A 100% pure abstract class is nothing but an interface
...
Example:
class Test(ABC):
@absractmethod
def method1(self):
pass
@absractmethod
def method2(self):
pass
The Purpose of Interface
An abstract class containing only abstract method acts as requirement specification, anyone can
provide an implementation in their way, and hence a single interface contain multiple applications in
their form
...
from abc import *
class CollegeAutomation(ABC): ##requirement apecification
@abstractmethod
def method1(self):pass
@abstractmethod
def method2(self):pass
@abstractmethod
def method3(self):pass
class AaruSoftImpl(CollegeAutomation):
def method1(self):
print("Method1 implementation")
def method2(self):
print("Method2 implementation")
def method3(self):
print("Method3 implementation")
d=AaruSoftImpl() ##creating an object and calling method1, method2 and method3
d
...
method2()
d
...
from abc import *
class CollegeAutomation(ABC): ##Interfcae, because it contains only abstract methods
@abstractmethod
def method1(self):pass
@abstractmethod
def method2(self):pass
@abstractmethod
def method3(self):pass
/*Abstract class because it provides implementation for only method1 and method2 and not for
method3*/
class AbsClass(CollegeAutomation):
def method1(self):
print("Method1 implementation")
def method2(self):
print("Method2 implementation")
/*Concrete class because it calls internally method1 and method2 and also providing
implementation to method3 */
class ConcreteClass(AbsClass):
def method3(self):
print("Method3 implementation")
c=ConcreteClass() #creating an object
c
...
method2()
c