Python Classes Objects Special Methods Inheritance, Polymorphism, Encapsulation
Python Classes Objects Special Methods Inheritance, Polymorphism, Encapsulation
LP (3 credits)
UNIT – 3
Python Inheritance, Polymorphism, Encapsulation
Abstraction
By
Dr. MK Jayanthi Kannan, B.E.,M.E.,MS.,MBA.,M.Phil., Ph.D.,
Professor School of Computing Science and Engineering,
AB 104, 8.30am- 5.pm
VIT Bhopal University, Bhopal-Indore Highway,
Kothrikalan, Madhya Pradesh - 466114.
email: jayanthi.m@vitbhopal.ac.in, Emp Id : 100600
Ph: +91 6379397594
UNIT – 3 Python Inheritance, Polymorphism, Encapsulation
Abstraction
The following topics we are going to discuss in UNIT 3
OOPs in Python Programming
• persistent storage of objects,
Principles of Object Orientation, • inheritance,
Classes in Python, • polymorphism,
Creating Classes, • operator
Instance Methods, • overloading,
Access Specification, • abstract classes,
data modeling,
• exception handling.
try block
# define a class
class Bike:
name = "" gear = 0
# create object of class
bike1 = Bike() # access attributes
and assign new values
bike1.gear = 11
bike1.name = "Mountain Bike“
print(f"Name: {bike1.name},
Gears: {bike1.gear} ")
# define a class
class Employee:
# define an attribute
employee_id = 0
2
1
1. Introduction to Object Oriented
Programming in Python
2
2
2. Difference between Object-Oriented and
Procedural Oriented Programming
Procedural-Oriented Programming
Object-Oriented Programming (OOP)
(Pop)
Object can move freely within member Data can move freely from function to
functions function within programs
Example:
2
4
# Python program to display the no of sides of polygonand find out
the area of the triangle
class Polygon:
def _init_(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]
def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]
def dispSides(self):
for i in range(self.n):
print("Side",i+1,"is",self.sides[i])
# Python program to display the no of sides of # Creating an instance of the Triangle class
polygonand find out the area of the triangle t = Triangle()
class Triangle(Polygon): # Prompting the user to enter the sides of the triangle
# Initializing the number of sides of the triangle to 3 t.inputSides()
by
# calling the _init_ method of the Polygon class # Displaying the sides of the triangle
def _init_(self): t.dispSides()
Polygon._init_(self,3)
# Calculating and printing the area of the triangle
def findArea(self): t.findArea()
a, b, c = self.sides
Output
# calculate the semi-perimeter Enter side 1 : 3
s = (a + b + c) / 2
Enter side 2 : 5
# Using Heron's formula to calculate the area of Enter side 3 : 4
the triangle Side 1 is 3.0
area = (s*(s-a)(s-b)(s-c)) ** 0.5
print('The area of the triangle is %0.2f' %area)
Side 2 is 5.0
Side 3 is 4.0
The area of the triangle is 6.00
Creating an Object and Class in python:
Example:
class employee():
def init (self,name,age,id,salary): //creating a function
self.name = name // self is an instance of a class
self.age = age
self.salary = salary
self.id = id
2
7
class Circle(object):
x1 = self.center[0]-rad y1 = self.center[1]-rad
x2 = self.center[0]+rad y2 = self.center[1]+rad
c1.company()
c1.companyname()
Object-Oriented Programming
methodologies:
Inheritance
Polymorphism
Encapsulation
Abstraction
3
2
Inheritance:
Python Inheritance
Like any other OOP languages, Python also supports the
concept of class inheritance.
# define
` a superclass
class super_class:
# attributes and method definition
# inheritance
class sub_class(super_class):
# attributes and method of super_class
# attributes and method of sub_class
Output: 22
Multilevel Inheritance:
Example:
print(emp1.age)
print(emp2.age)
Output: 22,23
Hierarchical Inheritance:
Example:
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)
Multiple Inheritance:
Example:
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)
Python Multiple Inheritance Syntax
class SuperClass1:
# features of SuperClass1
class SuperClass2:
# features of SuperClass2
class SuperClass:
# Super class code here
class DerivedClass1(SuperClass):
# Derived class 1 code here
class DerivedClass2(DerivedClass1):
# Derived class 2 code here
#Here, the DerivedClass1 class is derived from the SuperClass class, and the
DerivedClass2 class is derived from the DerivedClass1 class.
#Example: Python Multilevel Inheritance
class SuperClass:
# create an object of DerivedClass2
def super_method(self): d2 = DerivedClass2()
print("Super Class method called")
d2.super_method() # Output: "Super Class
# define class that derive from SuperClass method called"
class DerivedClass1(SuperClass):
def derived1_method(self): d2.derived1_method() # Output: "Derived
print("Derived class 1 method called") class 1 method called"
def derived2_method(self):
print("Derived class 2 method called")
Output
It means that DerivedClass2 inherits all the attributes and methods of both
DerivedClass1 and SuperClass.
You all must have used GPS for navigating the route, Isn‟t it
amazing how many different routes you come across for the
same destination depending on the traffic, from a
programming point of view this is called „polymorphism‟. It is
one such OOP methodology where one task can be performed
in several different ways. To put it in simple words, it is a
property of an object which allows it to take multiple forms.
62
Polymorphism
• Polymorphism is another important concept of object-
oriented programming. It simply means more than one form.
Compile-time Polymorphism
Run-time Polymorphism
66
Compile-time Polymorphism:
67
Example:
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")
68
def func(obj)://Method Overloading
obj.name()
obj.salary()
obj.age()
obj_emp1 = employee1()
obj_emp2 = employee2()
func(obj_emp1)
func(obj_emp2)
Output:
70
Example:
class employee():
def init (self,name,age,id,salary):
self.name = name
self.age = age
self.salary = salary
self.id = id
def earn(self):
pass
class childemployee1(employee):
def earn(self): //Run-time polymorphism
print("no money")
71
class childemployee2(employee):
def earn(self):
print("has money")
c = childemployee1
c.earn(employee)
d = childemployee2
d.earn(employee)
Output:
no money,
has money
72
Abstraction:
73
Method Overriding in Python Inheritance
class Animal:
# attributes and method of the parent class
name = ""
a = MyClass(True)
b = MyClass(False)
answer = answer + x
print(answer)
Difference between Method Overloading and Method Overriding in Python:
Method Overriding:
Method overriding is an example of run time polymorphism.
1. Implemented methods.
2. Un-implemented method.
Abstract Class in Python has 2 types based on the implementation,
1. Implemented methods:
• A method which has a both method name and method body,
that method is called an implemented method.
• They are also called concrete methods or non-abstract
methods. The methods which we have seen in the previous
chapters are implemented i.e having method name and body
as well.
2. Un-implemented methods:
• A method which has only method name and no method body,
that method is called an unimplemented method.
• They are also called as non-concrete or abstract methods.
How to declare an abstract method in Python:
Abstract methods, in python, are declared by using
@abstractmethod decorator.
>>> it.next()
‟c‟
>>> it.next()
Traceback (most recent call last):
File "<pyshell#6>", line 1, in -toplevel
it.next()
StopIteration
Iterators
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
Iterators
• Anything that can be done with generators can also be done with
class based iterators as described in the previous section.
• What makes generators so compact is that the __iter__() and
next() methods are created automatically.
• Another key feature is that the local variables and execution state
are automatically saved between calls.
• This made the function easier to write and much more clear than
an approach using class variables like self.index and self.data.
Generators
>>>
Here, we ask the user for input and if he/she presses Ctrl-d
i.e. the EOF (end of file) character, then Python raises an
error called EOFError.
import sys
try:
s = raw_input('Enter something --> ')
except EOFError:
print '\nWhy did you do an EOF on me?' sys.exit() # Exit the program
except:
print '\nSome error/exception occurred.'
# Here, we are not exiting the program
print 'Done'
Exception Handling
• We put all the statements that might raise an error in the
try block
class ShortInputException(Exception):
'''A user-defined exception class.'''
def __init__(self, length, atleast):
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter something --> ')
if len(s) < 3:
raise ShortInputException(len(s), 3)
Exception Handling