0% found this document useful (0 votes)
54 views

PWP Chapter 5

The document discusses object oriented programming in Python. It explains concepts like classes, objects, methods, inheritance and provides examples to demonstrate these concepts.

Uploaded by

Sanket Badave
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views

PWP Chapter 5

The document discusses object oriented programming in Python. It explains concepts like classes, objects, methods, inheritance and provides examples to demonstrate these concepts.

Uploaded by

Sanket Badave
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

Name of Staff: Mr. P. S. Bhandare


Name of Subject: Programming with Python
Subject code: 22616
Class: TYCO
Department: Computer Engineering

Unit No. 5
Object Oriented Programming
in Python
by
P. S. Bhandare

College of Engineering (Polytechnic),


Pandharpur

Hours: 08
Marks: 12

1|Page
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

Syllabus:
 5.1 Creating Classes and Objects.
 5.2 Method Overloading and Overriding.
 5.3 Data Hiding.
 5.4 Data abstraction.
 5.5 Inheritance and composition classes
 5.6 Customization via inheritance specializing inherited methods.

2|Page
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

About Title of Chapter:


 The title of chapter Python operators & control statements” tells that
this chapter includes study of operator & control statements that can
be used in various expressions.
 Also, it includes study related to looping statement to solve the
different problems.
About Central Idea of Chapter:
 The central idea of chapter is that by studying this chapter student
will learn new programming concept with syntax and example to
write & execute python programs.
About Importance of Chapter:
 This is chapter is important because this will introduce basic syntax
and example to write python programs to solve real life problems like
control statements & looping statements.
Outcomes of Chapter:
1. Create classes and objects to solve the given problem
2. Write Python code for data hiding for the given problem.
3. Write Python code using data abstraction for the given problem.
4. Write Python program using inheritance for the given problem

3|Page
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

Introduction:
We know that a class is a model or plan to create objects. This means, we write a class
with the attributes and actions of objects. Attributes are represented by variables and
actions are performed by methods. So, a class contains variable and methods. The same
variables and methods are also available in the objects because they are created from
the class. These variables are also called 'instance variables because they are created
inside the instance (i.e, object).
Please remember the difference between a function and a method. A function written
inside a class is called a method. Generally, a method is called using one of the following
two ways:
classname.methodname()
instancename.methodname()

The general format of a class is given as follows:


Class Classname(object):
"""docstring describing the class """
attributes
Def __init__ (self):
def method1():
def method2():

Creating a Class
A class is created with the keyword class and then writing the Classname. After the
Classname, 'object' is written inside the Classname. This 'object' represents the base
class name from where all classes in Python are derived. Even our own classes are also
derived from 'object' class. Hence, we should mention 'object' in the parentheses. Please
note that writing 'object' is not compulsory since it is implied.
The docstring is a string which is written using triple double quotes or triple single
quotes that gives the complete description about the class and its usage. The docstring is
used to create documentation file and hence it is optional, 'attributes' are nothing but
variables that contains data. __init__(self) is a special method to initialize the variables,
method1() and method2(), etc. are methods that are intended to process variables.
If we take 'Student' class, we can write code in the class that specifies the attributes and
actions performed by any student. For example, a student has attributes like name, age,
marks, etc. These attributes should be written inside the Student class as variables.
Similarly, a student can perform actions like talking, writing, reading, etc. These actions

4|Page
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

should be represented by methods in the Student class. So, the class Student contains
these attributes and actions, as shown here:
class Student: #another way is: class Student(object):
definit (self):
self.name = ‘Poly’
self.age=20
self.marks=900
def talk(self):
print("Hi, I am’, self.name)
print("My age is', self.age)
print("My marks are', self.marks)
Observe that the keyword class is used to declare a class. After this, we should write the
class name. So, Student' is our class name. Generally, a class name should start with a
capital letter, hence 'S' is capital in Student'. In the class, we write attributes and
methods. Since in Python, we cannot declare variables, we have written the variables
inside a special method, ie. __init__(). This method is useful to initialize the variables.
Hence, the name init. The method name has two underscores before and after. This
indicates that this method is internally defined and we cannot call this method explicitly.
Observe the parameter self written after the method name in the parentheses. 'self’ is a
variable that refers to current class instance. When we create an instance for the
Student class, a separate memory block is allocated on the heap and that memory
location is by default stored in 'self’. The instance contains the variables 'name', 'age',
'marks' which are called instance variables. To refer to instance variables, we can use
the dot operator notation along with self a 'self.name', 'self.age' and 'self.marks"
See the method talk(). This method also takes the self variable as parameter method
displays the values of the variables by referring them using self.
The methods that act on instances (or objects) of a class are called instance methods.
Instance methods use 'self’ as the first parameter that refers to the location of the
instance in the memory. Since instance methods know the location of instance, they can
act on the instance variables. In the previous code, the two methods __init__(self) and
talk(self) are called instance methods.
In the Student class, a student is talking to us through talk() method. He is introducing
himself to us, as shown here:
Hi, I am Poly
My age is 20
My marks are 900

5|Page
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

This is what the talk() method displays. Writing a class like this is not sufficient. It
should be used. To use a class, we should create an instance (or object) to the class.
Instance creation represents allotting memory necessary to store the actual data of the
variables, i.e., Poly, 20 and 900. To create an instance, the following syntax is used:
instancename =Classname()
So, to create an instance (or object) to the Student class, we can write as:
s1 = Student()
Here, 's1' is nothing but the instance name. When we create an instance like this, the
following steps will take place internally:
1. First of all, a block of memory is allocated on heap. How much memory is to be
allocated is decided from the attributes and methods available in the Student class.
2. After allocating the memory block, the special method by the name _init_(self) is
called internally. This method stores the initial data into the variables. Since this method
is useful to construct the instance, it is called 'constructor.
3. Finally, the allocated memory location address of the instance is returned into 1
variable. To see this memory location in decimal number format, we can use id()
function as id(s1).
Now, 's1' refers to the instance of the Student class. Hence any variables or methods in
the instance can be referenced by 's1' using dot operator as:
s1.name
sl.age
s1.marks
s1.talk()
Program to accept & display data:
class student:
def accept(self):
self.nm=input("Enter name:")
self.ag=int(input("Enter Age: "))
self.mk=int(input("Enter Marks:"))
def display(self):
print("Name: ",self.nm)
print("Age: ",self.ag)
print("Marks: ",self.mks)

s1=student()
s1.accept()
s1.display()

6|Page
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

The Self Variable

'self is a default variable that contains the memory address of the instance of the current
class. So, we can use 'self to refer to all the instance variables and instance methods.
When an instance to the class is created, the instance name contains the memory
location of the instance. This memory location is internally passed to 'self. For example,
we create an instance to Student class as:

s1= Student()

Here, s1 contains the memory address of the instance. This memory address is
internally and by default passed to 'self’ variable. Since 'self' knows the memory address
of the instance, it can refer to all the members of the instance. We use 'self' in two ways:
The 'self variable is used as first parameter in the constructor as:
Def__init__ (self):
In this case, 'self' can be used to refer to the instance variables inside the constructor.
'self' can be used as first parameter in the instance methods as:
def talk(self):
Here, talk() is instance method as it acts on the instance variables. If this method wants
to act on the instance variables, it should know the memory location of the instance
variables. That memory location is by default available to the talk() method through
'self'.

Constructor
A constructor is a special method that is used to initialize the instance variables of a
class. In the constructor, we create the instance variables and initialize them with some
starting values. The first parameter of the constructor will be 'self’ variable that
contains the memory address of the instance. For example,
Def__init__ (self):
self.name ='Poly'
self.marks=900
Here, the constructor has only one parameter, 'self'. Using 'self.name' and 'self.marks',
we can access the instance variables of the class. A constructor is called at the time of
creating an instance. So, the above constructor will be called when we create an instance
as:
s 1=student
Here, 's1' is the name of the instance. Observe the empty parentheses after the class
name 'Student'. These empty parentheses represent that we are not passing any values
to the constructor. Suppose, we want to pass some values to the constructor, then we
have to pass them in the parentheses after the class name. Let's take another example.
We can
write a constructor with some parameters in addition to 'self' as:
def __init__(self,n=” ”,m=0):
self.name=n

7|Page
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

self.marks=500

Here, the formal arguments are 'n' and m' whose default values are given as “ ” (None)
and 0 (zero). Hence, if we do not pass any values to constructor at the time of creating
an instance, the default values of these formal arguments are stored into name and
marks variables. For example,
s1=Student()
Since we are not passing any values to the instance, None and zero are stored into name
and marks. Suppose, we create an instance as:
s1=student( “Polytech”, 880)

In this case, we are passing two actual arguments: ‘Polytech' and 880 to the Student
instance. Hence these values are sent to the arguments 'n' and 'm' and from there stored
into name and marks variables.

A Python program to create Student class with a constructor having more than one
parameter.

class Student:
def __init__ (self, n'', m=0):
self.name=n
self.marks = m
def display(self):
print( ‘Hi' , self.name)
print('Your marks', self.marks)
s= Student()
s.display()
print('------------------------------- ')
#constructor is called with 2 arguments
s1= Student('Polytech', 880)
sl.display()
print('------------------------------- ')

Output:
Hi
Your marks 0
Hi Polytech
Your marks 880

Types of Variables

The variables which are written inside a class are of 2 types:

1. Instance variables

8|Page
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

2. Class variables or Static variables

Instance variables are the variables whose separate copy is created in every instance (or
object). For example, if 'x' is an instance variable and if we create 3 instances, there will
be 3 copies of x' in these 3 instances. When we modify the copy of 'x' in any instance, it
will not modify the other two copies. Consider Program 3.

A Python program to understand instance variables.

#instance vars example


class Sample:
#this is a constructor.
def __init(self):
self. x = 10
#this is an instance method.
def modify(self):
self.x+=1
#create 2 instances
s1 = Sample()
s2 =Sample()
print('x in sl=' s1.x)
print('x in s * 2 = s2.x)
#modify x in
sl .modify()
print('x in sl=' s1.x)
print('x in s * 2 = s2.x)

Output:
x in s1= 10
x in s2= 10
x in s1= 11
x in s2 = 10

Instance variables are defined and initialized using a constructor with 'self parameter.
Also, to access instance variables, we need instance methods with 'self as first
parameter. It is possible that the instance methods may have other parameters in
addition to the 'self parameter. To access the instance variables, we can use self.variable
as shown in Program It is also possible to access the instance variables from outside the
class, as: instancename variable, e.g. sl.x.

Unlike instance variables, class variables are the variables whose single copy is available
to all the instances of the class. If we modify the copy of class variable in an instance, it
will modify all the copies in the other instances. For example, if 'x' is a class variable and
if we create 3 instances, the same copy of x' is passed to these 3 instances. When we
modify the copy of 'x' in any instance using a class method, the modified copy is sent to
the other two instances. Class variables are also called static variables.
9|Page
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

A Python program to understand class variables or static variables.


#class vars or static vars example
class Sample:
#this is a class var
x = 10
#this is a class method.
@classmethod
def modify(cls):
cls.x+=1

#create 2 instances
s1 = Sample()
s2= Sample()
print('x in sl=', s1.x)
print('x in s2 =’ s2.x)
#modify x in sl
s1.modify()
print('x in sl=', s1.x)
print('x in s2=', s2.x)

Output:
x in s1= 10
x in s2= 10
x in s1= 11
x in s2= 11

The class variable 'x' is defined in the class and initialized with value 10. A method by
the name 'modify' is used to modify the value of x'. This method is called 'class method'
since it is acting on the class variable. To mark this method as class method, we should
use built-in decorator statement @classmethod. For example,

@classmethod # this is a decorator


def modify(cls):
cls.x+=1

A class method contains first parameter by default as 'cls' with which we can access the
class variables. For example, to refer to the class variable 'x', we can use cls .x . We can
also write other parameters in the class method in addition to the 'cls' parameter. The
point is that the class variables are defined directly in the class. To access class variables,
we need class methods with 'cls' as first parameter. We can access the class variables
using the class methods as: cls.variable. If we want to access the class variables from
outside the class, we can use: classname.variable, e.g. Sample.x.

10 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

Types of Methods

By this time, we got some knowledge about the methods written in a class. The purpose
of a method is to process the variables provided in the class or in the method. We
already know that the variables declared in the class are called class variables (or static
variables) and the variables declared in the constructor are called instance variables. We
can classify the methods in the following 3 types:

1. Instance methods
(a) Accessor methods
(b) Mutator methods
2. Class methods
3. Static methods

Instance Methods

Instance methods are the methods which act upon the instance variables of the class.
Instance methods are bound to instances (or objects) and hence called as:
instancename.method(). Since instance variables are available in the instance, instance
methods need to know the memory address of the instance. This is provided through
'self variable by default as first parameter for the instance method. While calling the
instance methods, we need not pass any value to the 'self' variable.

Following program is an extension to our previous Student class. In this program, we are
creating a Student class with a constructor that defines 'name' and 'marks' as instance
variables. An instance method display() will display the values of these variables. We
added another instance methods by the name calculate() that calculates the grades of
the student depending on the 'marks'.

A Python program using a student class with instance methods to process the data of
several students.

#instance methods to process data of the objects


class Student:
definit (self, n=’ ’ m=0):
self.name = n
self.marks = m
#this is an instance method.
def display(self):
print(‘Hi’ , self.name)
print('Your marks', self.marks)
#to calculate grades based on marks.
def calculate(self):

11 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

if(self.marks>=600):
print('You got first grade')
elif(self.marks>=500):
print('You got second grade')
elif(self.marks>=350):
print('You got third grade')
else:
print('You are failed')
n = int(input('How many students? '))
i=0
while(i<n):
name = input('Enter name: ')
marks = int(input('Enter marks: '))

s=student(name,marks)
s.display()
s.calculate()
i+=1
print(“-----------------------”)

Features of OOP:
1. Encapsulation
Encapsulation is a mechanism where the data (variables) and the code (methods)
that act on the data will bind together. For example, if we take a class, we write the
variables and methods inside the class. Thus, class is binding them together. So
encapsulation. class is an example for Encapsulation.
The variables and methods of a class are called 'members' of the class. All the
members of a class are by default available outside the class. That means they are public
by default. Public means available to other programs and classes. Python follows
Uniform Access Principle that says that in OOPS, all the members of the class whether
they are variables or methods should be accessible in a uniform manner. So, Python
variables and methods are available outside alike. That means both are public by
default. Usually, in C++ and Java languages, the variables are kept private, that means
they are not available outside the class and the methods are kept public meaning that
they are available to other programs. But in Python, both the variables and methods are
public by default. Encapsulation isolates the members of a class from the members of
another class. The reason is when objects are created, each object shares different
memory and hence there will not be any overwriting of data. This gives an advantage to
the programmer to use same names for the members of two different classes. For
example, a programmer can declare and use the variables like 'id', 'name', and 'address'
in different classes like Employee, Customer, or Student classes.

Encapsulation in Python
Encapsulation is nothing but writing attributes (variables) and methods inside a class.
The methods process the data available in the variables. Hence data and code are

12 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

bundled up together in the class. For example, we can write a Student class with 'id' and
'name as attributes along with the display() method that displays this data. This Student
class becomes an example for encapsulation.
#a class is an example for encapsulation
class Student: #to declare and initialize the variables
def __init_(self):
self. id = 10
self.name = 'Raju'
#display students details
def display(self):
print(self.id)
print(self.name)

Observe the first method: def __init__(self). This is called a special function since its
name is starting and ending with two underscores. If a variable or method name starts
and ends with two underscores, they are built-in variables or methods which are
defined for a specific purpose. The programmer should not create any variable or
method like them. It means we should not create variables or methods with two
underscores before and after their names.
The purpose of the special method def __init__(self) is to declare and initialize the
instance variables of a class. Instance variables are the variables whose copy is available
in the object (or instance). The first parameter for this method is 'self' that represents
the object (or instance) of the present class. So, self.id refers to the variable in the object.
In the Student class, we have written another method by the name display() that
displays the instance variables.

Data hiding

There may be a lot of data, a class contains and the user does not need the entire data.
The user requires only some part of the available data. In this case, we can hide the
unnecessary data from the user and expose only that data that is of interest to the user.
This is called abstraction.

A good example for abstraction is a car. Any car will have some parts like engine,
radiator, battery, mechanical and electrical equipment etc. The user of the car (driver)
should know how to drive the car and does not require any knowledge of these parts.
For example driver is never bothered about how the engine is designed and the internal
parts of the engine. This is why the car manufacturers hide these parts from the driver
in a separate panel, generally at the front of the car.
The advantage of abstraction is that every user will get his own view of the data
according to his requirements and will not get confused with unnecessary data. A bank
clerk should see the customer details like account number, name and balance amount in
the account. He should not be entitled to see the sensitive data like the staff salaries,
profit or loss of the bank, interest amount paid by the bank, loans amount to be
recovered, etc. Hence, such sensitive data can be abstracted from the clerk's view. The

13 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

bank manager may, however, require the sensitive data and so it will be provided to the
manager.

Data hiding in Python

In languages like Java, we have keywords like private, protected and public to implement
various levels of abstraction. These keywords are called access specifiers. In Python,
such words are not available. Everything written in the class will come under public.
That means everything written in the class is available outside the class to other people.
Suppose, we do not want to make a variable available outside the class or to other
members inside the class, we can write the variable with two double scores before it as:
var. This is like a private variable in Python. In the following example, y' is a private
variable since it is written as: y.

class Myclass:
#this is constructor.
def __init__(self):
self.__y=3
Now, it is not possible to access the variable from within the class or out of the class as:
m =Myclass()
print(m.y) #error

The preceding print() statement displays error message as: AttributeError: 'Myclass'
object has no attribute y'. Even though, we cannot access the private variable in this way,
it is possible to access it in the format: instancename._Classname_var. That means we are
using Classname differently to access the private variable. This is called name mangling.
In name mangling, we have to use one underscore before the classname and two
underscores after the classname. Like this, using the names differently to access the
private variables is called name mangling. For example, to display a private variable y'
value, we can write:

print(m. __Myclass__y)
# display private variable y

The same statement can be written inside the method as: print(self. __Myclass__z). When
we use single underscore before a variable as_var, then that variable or object will not be
imported into other files. The following code represents the public and private variables
and how to access them.

#understanding public and private variables


class Myclass:
def__init__(self):
self.x = 1 #public var
self.__ y = 2 # private var
#instance method to access variables
def display(self):
14 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

print(self.x) # x is available directly


print(self._Myclass__y) #name mangling required

print('Accessing variables through method:')


m = Myclass()
m.display()
print('Accessing variables through instance:')
print ( m .x) #x is available directly
print(m._myclass__y) #name mangling required

Output:
Accessing variables through method:
1
2
Accessing variables through instance:
1
2

Data Abstraction
Data abstraction is one of the most essential concepts of Python OOPs which is used to
hide irrelevant details from the user and show the details that are relevant to the users.
For example, the readers of geeksforgeeks only know that a writer can write an article
on geeksforgeeks, and when it gets published readers can read the articles but the
reader is not aware of the background process of publishing the article.
A simple example of this can be a car. A car has an accelerator, clutch, and break and we
all know that pressing an accelerator will increase the speed of the car and applying the
brake can stop the car but we don’t the internal mechanism of the car and how these
functionalities can work this detail hiding is known as data abstraction.
It enables programmers to hide complex implementation details while just showing
users the most crucial data and functions. This abstraction makes it easier to design
modular and well-organized code, makes it simpler to understand and maintain,
promotes code reuse, and improves developer collaboration.

Abstraction classes in Python


Abstract class is a class in which one or more abstract methods are defined. When a
method is declared inside the class without its implementation is known as abstract
method.

Abstract Method: In Python, abstract method feature is not a default feature. To create
abstract method and abstract classes we have to import the “ABC” and
“abstractmethod” classes from abc (Abstract Base Class) library. Abstract method of
base class force its child class to write the implementation of the all abstract methods
defined in base class. If we do not implement the abstract methods of base class in the
child class then our code will give error. In the below code method_1 is a abstract
method created using @abstractmethod decorator.

15 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

from abc import ABC ,abstractmethod


class myclass:
def __init__(self):
self.a=10
self.b=20
self.c=30
@abstractmethod
def show():
pass

def mul(self):
print("Concrete method")
print(self.a*self.b*self.c)

class democlass(myclass):
def show(self):
print("Abstract method")
print(self.a+self.b+self.c)

d=democlass()
d.show()
d.mul()

Inheritance

Creating new classes from existing classes, so that the new classes will acquire all the
features of the existing classes is called Inheritance. A good example for Inheritance in
nature is parents producing the children and children inheriting the qualities of the
parents.

Let's take a class A with some members i.e., variables and methods. If we feel another
class B wants almost same members, then we can derive or create class B from A as:

class B(A):

Now, all the features of A are available to B. If an object to B is created, it contains all the
members of class A and also its own members. Thus, the programmer can access and
use all the members of both the classes A and B. Thus, class B becomes more useful. This
is called inheritance. The original class (A) is called the base class or super class and the
derived class (B) is called the sub class or derived class.

16 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

There are three advantages of inheritance. First, we can create more useful classes
needed by the application (software). Next, the process of creating the new classes is
very easy, since they are built upon already existing classes. The last, but very important
advantage is managing the code becomes easy, since the programmer creates several
classes in a hierarchical manner, and segregates the code into several modules.

An Example for Inheritance in Python

Here, we take a class A with two variables 'a' and 'b' and a method, method 1 (). Since all
these members are needed by another class B, we extend class B from A. We want some
additional members in B, for example a variable 'c' and a method, method2(). So, these
are written in B. Now remember, class B can use all the members of both A and B. This
means the variables 'a','b','c 'and also the methods display() and calculate() are available
to class B. That means all the members of A are inherited by B.
class A:
a=10
def display(cls):
print(cls.a)
class B(A):
b=20
def calculate(cls):
cls.c=cls.a+cls.b
print(cls.c)
b1=B();
b1.display();
b1.calculate()

Types of inheritance :
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance

1. Single Inheritance:
Single inheritance enables a derived class to inherit properties from a single parent
class, thus enabling code reusability and the addition of new features to existing code.

# single inheritance
# Base class

17 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

class Parent:
def func1(self):
print("This function is in parent class.")
# Derived class
class Child(Parent):
def func2(self):
print("This function is in child class.")
# Driver's code
object = Child()
object.func1()
object.func2()
2. Multiple Inheritance:
When a class can be derived from more than one base class this type of inheritance is
called multiple inheritances. In multiple inheritances, all the features of the base classes
are inherited into the derived class.

# multiple inheritance
# Base class1
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
# Base class2
class Father:
fathername = ""
def father(self):
print(self.fathername)
# Derived class
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
# Driver's code
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()

3. Multilevel Inheritance :

18 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

In multilevel inheritance, features of the base class and the derived class are further
inherited into the new derived class. This is similar to a relationship representing a child
and a grandfather.

# multilevel inheritance
class Base:
def seta(self):
self.a=33
class Derived1(Base):
def setb(self):
self.b=11
class Derived2(Derived1):
def setc(self):
self.c=22
def calculate(self):
self.d=self.a+self.b+self.c
print("Total: ",self.d)
d2=Derived2()
d2.seta()
d2.setb()
d2.setc()
d2.calculate();

4. Hierarchical Inheritance:
When more than one derived class are created from a single base this type of
inheritance is called hierarchical inheritance. In this program, we have a parent (base)
class and two child (derived) classes.

# Hierarchical inheritance
# Base class
class Parent:

19 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

def func1(self):
print("This function is in parent class.")
# Derived class1
class Child1(Parent):
def func2(self):
print("This function is in child 1.")
# Derivied class2
class Child2(Parent):
def func3(self):
print("This function is in child 2.")
# Driver's code
object1 = Child1()
object2 = Child2()
object1.func1()
object1.func2()
object2.func1()
object2.func3()

Hybrid Inheritance:
Inheritance consisting of multiple types of inheritance is called hybrid inheritance.

# hybrid inheritance
class School:
def func1(self):
print("This function is in school.")
class Student1(School):
def func2(self):
print("This function is in student 1. ")
class Student2(School):
def func3(self):
print("This function is in student 2.")
class Student3(Student1, School):
def func4(self):
print("This function is in student 3.")
# Driver's code
object = Student3()

20 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

object.func1()
object.func2()

super() function
Python super function provides us the facility to refer to the parent class explicitly. It is
basically useful where we have to call superclass functions. It returns the proxy object
that allows us to refer parent class by ‘super’.
Python Super function provides us the flexibility to do single level or multilevel
inheritances and makes our work easier and comfortable. Keep one thing in mind that
while referring the superclass from subclass, there is no need of writing the name of
superclass explicitly.

class Parent:
def __init__(self, txt):
self.message = txt

def printmessage(self):
print(self.message)

class Child(Parent):
def __init__(self, txt):
super().__init__(txt)
x = Child("Hello, and welcome!")
x.printmessage()

Polymorphism

The word 'Polymorphism' came from two Greek words 'poly' meaning 'many' and
'morphos' meaning 'forms'. Thus, polymorphism represents the ability to assume
several different forms. In programming, if an object or method is exhibiting different
behavior in different contexts, it is called polymorphic nature.
Polymorphism provides flexibility in writing programs in such a way that the
programmer uses same method call to perform different operations depending on the
requirement.

Polymorphism in Python:
When a function can perform different tasks, we can say that it is exhibiting
polymorphism. A simple example is to write a function as:
def add(a, b):
print(a+b)
Since in Python, there the variables are not declared explicitly, we are passing two
variables 'a', and 'b' to add() function where they are added. While calling this function,
if we pass two integers like 5 and 15, then this function displays 15. If we pass two
strings, then the same function concatenates or joins those strings. That means the same
function is adding two integers or concatenating two strings. Since the function is

21 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

performing two different tasks, it is said to exhibit polymorphism. Now, consider the
following example:
#a function that exhibits polymorphism
def add (a, b):
print (a + b)
#call add() and pass two integers
add(5, 10) #displays 15
#call add() and pass two strings
add("Core", "Python") # displays CorePython

Method overloading
Method overloading is one concept of Polymorphism. It comes under the elements of
OOPS. It is actually a compile-time polymorphism. It is worked in the same method
names and different arguments. Here in Python also supports oops concepts. But it is
not oops based language. It also supports this method overloading also.
Normally in python, we don’t have the same names for different methods. But
overloading is a method or operator to do the different functionalities with the same
name. i.e methods differ their parameters to pass to the methods whereas operators
have differed their operand.

Advantages of Method Overloading in Python.


Normally methods are used to reduce complexity. Method overloading is even it reduce
more complexity in the program also improves the clarity of code. It is also used for
reusability.
It has some disadvantages also when creating more confusion during the inheritance
concepts. In python, we create a single method with different arguments to process the
Method Overloading. Here we create a method with zero or more parameters and also
define the methods based on the number of parameters.
class Addition:
def add(self,a,b,c=0):
if c>0:
print(a+b+c)
else:
print(a+b)

obj=Addition()
obj.add(10,20)
obj.add(10,20,30)

Method Overriding in Python


Method overriding is an ability of any object-oriented programming language that
allows a subclass or child class to provide a specific implementation of a method that is
already provided by one of its super-classes or parent classes. When a method in a
subclass has the same name, same parameters or signature and same return type(or

22 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

sub-type) as a method in its super-class, then the method in the subclass is said
to override the method in the super-class.

The version of a method that is executed will be determined by the object that is used to
invoke it. If an object of a parent class is used to invoke the method, then the version in
the parent class will be executed, but if an object of the subclass is used to invoke the
method, then the version in the child class will be executed. In other words, it is the type
of the object being referred to (not the type of the reference variable) that determines
which version of an overridden method will be executed.
# method overriding
# Defining parent class
class Parent():
# Constructor
def __init__(self):
self.value = "Inside Parent"
# Parent's show method
def show(self):
print(self.value)
# Defining child class
class Child(Parent):
# Constructor
def __init__(self):
self.value = "Inside Child"
# Child's show method
def show(self):
print(self.value)
# Driver's code
obj1 = Parent()
obj2 = Child()
obj1.show()
obj2.show()

Calling the Parent’s method within the overridden method:


Parent class methods can also be called within the overridden methods. This can
generally be achieved by two ways.
Using Classname: Parent’s class methods can be called by using the
Parent classname.method inside the overridden method.

23 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

Example:
class Parent():
def show(self):
print("Inside Parent")
class Child(Parent):
def show(self):
# Calling the parent's class
# method
Parent.show(self)
print("Inside Child")
# Driver's code
obj = Child()
obj.show()

Using Super(): Python super() function provides us the facility to refer to the parent
class explicitly. It is basically useful where we have to call superclass functions. It returns
the proxy object that allows us to refer parent class by ‘super’.

class Parent():
def show(self):
print("Inside Parent")
class Child(Parent):
def show(self):
# Calling the parent's class
# method
super().show()
print("Inside Child")
# Driver's code
obj = Child()
obj.show()

Specializing Inherited Methods


class Super:
def method(self):
print 'in Super.method'
class Sub(Super):
def method(self):
print 'starting Sub.method'
Super.method(self)
print 'ending Sub.method'
x = Super( )
x.method( )
x = Sub( )
x.method( )

24 | P a g e
Prashant S. Bhandare
Unit V: Object Oriented Programming in Python Programming with “Python” (22616)

Classes Are Customized by Inheritance


lass FirstClass:
def setdata(self, value):
self.data = value
def display(self):
print self.data
class SecondClass(FirstClass):
def display(self):
print 'Current value = "%s"' % self.data

z = SecondClass( )
z.setdata(42)
z.display( )

25 | P a g e
Prashant S. Bhandare

You might also like