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
...
m1()
##The output is:
File "C:/Users/User/
...
py", line 14, in
s=SubTest()
TypeError: Can't instantiate abstract class SubTest with abstract methods m2
The following example contains an abstract class with two abstract methods, and in the
child class, we are implementing both methods m1 and m2, and hence we can create an
object, or we can perform instantiation
...
m1()
s
...
from abc import *
class Test(ABC):
def m1(self):
print("non-abstract method")
@abstractmethod
def m2(self):
pass
class SubTest(Test):
def m2(self):
print("m2 method implementation")
s=SubTest()
s
...
m2()
The output is:
==================
A class that is derived from an abstract class cannot be instantiated unless all of its
abstract methods are overridden
...
This impression is wrong: An abstract method can have an implementation in
the abstract class! Even if they are implemented, designers of subclasses will be forced
to override the implementation
...
This enables providing some basic
functionality in the abstract method, which can be enriched by the subclass
implementation
...
do_something()
print("The enrichment from AnotherSubclass")
x = AnotherSubclass()
x
...
noofsides()
K = Quadrilateral()
K
...
noofsides()
K = Hexagon()
K
...
move()
K = Snake()
K
...
move()
K = Lion()
K
...
In this
case, the Python class management is used to recognize PluginImplementation as implementing
the abstract PluginBase
...
The concrete class provides an implementation of
abstract methods, the abstract base class can also provide an implementation by invoking the
methods via super()
...
class R(ABC):
def rk(self):
print("Abstract Base Class")
class K(R):
def rk(self):
super()
...
rk()
Example-6
Abstract Class Instantiation :
Abstract classes are incomplete because they have methods that have nobody
...
So we use an abstract class as a template and
according to the need, we extend it and build on it before we can use it
...
When we create an object for the
abstract class it raises an error
...
py",
line 19, in
c=Animal()
TypeError: Can't instantiate abstract class Animal
with abstract methods move
class Snake(Animal):
def move(self):
print("I can crawl")
class Dog(Animal):
def move(self):
print("I can bark")
class Lion(Animal):
def move(self):
print("I can roar")
c=Animal()
===============================================
Python Interfaces
An abstract class can contain both abstract and non-abstract methods if an abstract class contain
only abstract method, then the class is called an interface
...
An interface acts as a service requirement
specification
...
The following example demonstrates the purpose of the interface
...
method1()
d
...
method3()
The output is:
The difference between Interface vs Abstract class vs Concrete class
Interface
Abstract class
Concrete class
If we do not know anything about
implementation and we want to
know requirement specification,
then we should go for Interface
If we are talking about
implementation but not
wholly, then we should go
for abstract class
If we are talking about complete
implementation and ready to
provide service, then we should
go for a concrete class
The following example demonstrates the difference between interface, abstract class, and concrete
class