Python Workshop-Day6
Python Workshop-Day6
and
Workshop on “Introduction
EXCEPTION
to Python”
28/06/2018
Workshop on “Introduction to
Python”
Department Of
Computer Science
Engineering
1
SKFGI, Mankundu
Different Programming Models
Both are programming processes whereas OOP stands for “Object
resolve the problem using just the right approach or you can say ‘paradigm’.
2
What is Procedure Oriented Programming (POP)?
a computer can understand what to do. The program is divided into small
Procedures correspond to functions and each function has its own purpose.
3
What is Object Oriented Programming (OOP)?
OOP is a high-level programming language where a program is divided into
small chunks called objects using the object-oriented model, hence the
4
Difference Between POP between OOP:-
BASIS FOR
POP OOP
COMPARISON
oriented .
functions.
. of a class.
"protected".
5
operators. operators.
Data hiding & security There is no proper way Data is hidden in three
data security
increases.
Pascal C#.NET.
6
Object Oriented Programming
Python is an object-oriented programming language. It allows us to develop
applications using Object Oriented approach. In Python, we can easily create
and use classes and objects.
Major principles of object-oriented programming system are given below
1. Class
2. Object
3. Inheritance
4. Polymorphism
5. Encapsulation
6. Data Abstraction
1.1What is a class?
<statement-N>
The user defined objects are created using the class keyword. The class is a
blueprint that defines a nature of a future object. From classes we construct
7
instances. An instance is a specific object created from a particular class. For
example, Huck might be an instance of a Dog class.
Syntax:-
object_name=class name()
prog2:-
class MyClass1:
8
v1 = "supreme"
obj1 = MyClass1()
print(obj1.v1)
Prog3:-
class MyClass2:
v= 7
obj = MyClass2()
obj1 = MyClass2()
print(obj.v)
print(obj1.v)
Prog4:-
class MyClass3:
var = 7
obj = MyClass3()
obj1 = MyClass3()
print(obj.var)
print(obj1.var)
obj1.var=9
print(obj.var)
print(obj1.var)
1.3.Methods
A method defines operations that we can perform with our objects.Method
is a function that is associated with an object. When you define methods,
you will need to always provide the first argument to the method with a self
keyword.The self argument refers to the object itself. That is, the object that
has called the method. This means that even if a method that takes no
arguments, it should be defined to accept the self. Similarly, a function
defined to accept one parameter will actually take two-self and the
parameter.
9
Methods are functions defined inside the body of a class. They are used to
perform operations with the attributes of our objects. Methods are essential
in the encapsulation concept of the OOP paradigm. For example, we might
have a connect() method in our AccessDatabase class. We need not to be
informed how exactly the method connect connects to the database. We only
know that it is used to connect to a database. This is essential in dividing
responsibilities in programming, especially in large applications.
Example:-
class Circle():
pi = 3.141592
def __init__(self, radius=1):
self.radius = radius
def area(self):
return self.radius * self.radius * Circle.pi
def setRadius(self, radius):
self.radius = radius
def getRadius(self):
return self.radius
c = Circle(5)
print(c.getRadius())
print(c.area())
c.setRadius(1)
print(c.getRadius())
print(c.area())
In the code example, we have a Circle class. We define three new methods.
The setRadius() method sets a new value for the radius attribute.
c.setRadius(1)
10
The method is called on an instance object. The c object is paired with
the self parameter of the class definition. The number 1 is paired with
the radius parameter.
Example:-
class Methods():
def __init__(self):
self.name = 'Methods'
def getName(self):
return self.name
m = Methods()
print(m.getName())
print(Methods.getName(m))
Prog1:-
class MyClass:
def display(self):
print("supreme")
obj = MyClass()
obj. display()
Prog2:-
class MyClass:
def display1(self,v):
11
print("This is a message inside the class.",v)
obj = MyClass()
obj. display1 (7)
Example:-
class Book():
def __init__(self, title, author, pages):
print("A book is created")
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return "Title:{0} , author:{1}, pages:{2} ".format(
self.title, self.author, self.pages)
def __len__(self):
return self.pages
def __del__(self):
print("A book is destroyed")
book = Book("Inside Steve's Brain", "Leander Kahney", 304)
print(book)
print(len(book))
del book
In our code example, we have a book class. Here we introduce four special
methods: __init__(), __str__(), __len__() and __del__().
book = Book("Inside Steve's Brain", "Leander Kahney", 304)
Here we call the __init__() method. The method creates a new instance of a
Book class.
print(book)
12
The print keyword calls the __str__() method. This method should return an
informal string representation of an object.
print(len(book))
The len() function invokes the __len__() method. In our case, we print the
number of pages of our book.
del book
Prog2:-
class Addition:
def __init__(self, a, b):
self.s = a
self.k = b
13
def add(self):
c=x.s+x.k
print(c)
x = Addition(3,4.5)
x.add()
print(x.s,x.k)
Example:-
class Cat():
In this code example, we have a Cat class. The special method __init__() is
called automatically right after the object has been created.
def __init__(self, name):
self.name = name
missy = Cat('Missy')
lucky = Cat('Lucky')
14
Here we create two objects: cats Missy and Lucky. The number of
arguments must correspond to the __init__() method of the class definition.
The 'Missy' and 'Lucky' strings become the nameparameter of
the __init__() method.
print(missy.name)
print(lucky.name)
Here we print the attributes of the two cat objects. Each instance of a class
can have their own attributes.
Missy
Lucky
Example:-
class Person():
pass
p = Person()
p.age = 24
p.name = "Peter"
print("{0} is {1} years old".format(p.name, p.age))
p.age = 24
p.name = "Peter"
15
So far, we have been talking about instance attributes. In Python there are
also so called class object attributes. Class object attributes are same for all
instances of a class.
Example:-
class Cat:
species = 'mammal'
def __init__(self, name, age):
self.name = name
self.age = age
missy = Cat('Missy', 3)
lucky = Cat('Lucky', 5)
print(missy.name, missy.age)
print(lucky.name, lucky.age)
print(Cat.species)
print(missy.__class__.species)
print(lucky.__class__.species)
In our example, we have two cats with specific name and age attributes.
Both cats share some characteristics. Missy and Lucky are both mammals.
This is reflected in a class level attribute species. The attribute is defined
outside any method name in the body of a class.
print(Cat.species)
print(missy.__class__.species)
There are two ways how we can access the class object attributes: either via
the name of the Catclass, or with the help of a special __class__ attribute.
16
different instance of the same class. An example will make this easy to
understand.
Prog1:-
class ABC():
a=0 #class varible
def __init__(self,var):
ABC.a+=1
self.var=var #object variable
print("The object value is:",var)
print("The value of class variable is: ",ABC.a)
obj1=ABC(10)
obj2=ABC(20)
obj3=ABC(30)
1.8.Public and Private Data Members:-
Public variables are those variables that are defined in the class and can be
accessed from anywhere in the program.
Private variables are those variables that are defined in the class with a
double score prefix(__).These variables can be accessed only from within
the class and from nowhere outside the class.
Example:-
class ABC():
def __init__(self,var1,var2):
self.var1=var1
self.__var2=var2
def display(self):
print("From class method,var1=",self.var1)
print("From class method,var2=",self.__var2)
obj=ABC(10,20)
obj.display()
print("From main module,var1=",obj.var1)
print("From main module,var2=",obj.__var2)
1.8.1Private Methods:-
A private method can be accessed using the object name as well as the class
name from outside the class.
1.8.2 Public Method Example:-
17
class ABC():
def display(self,var):
print("From class method,var=",var)
obj=ABC()
obj.display(7)
Private Method Example:-
(Accessing approach is wrong)
class ABC():
def __display(self,var):
print("From class method,var=",var)
obj=ABC()
obj.__display(7)
CORRECT PROGRAM:-
class ABC():
def __display(self,var):
print("From class method,var=",var)
obj=ABC()
obj._ABC__display(7)
1.9. Inheritance:- Inheritance is a powerful feature in object oriented
programming. Inheritance is a feature of object-oriented programming. It
specifies that one object acquires all the properties and behaviors of parent
object. By using inheritance you can define a new class with a little or no
changes to the existing class. The new class is known as derived class or
child class and from which it inherits the properties is called base class or
parent class.
It provides re-usability of the code.
It refers to defining a new class with little or no modification to an existing
class. The new class is called derived (or child) class and the one from
which it inherits is called the base (or parent) class.
18
There are basically four types of Inheritance-
1.Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hybrid Inheritance
1.9.1Single Inheritance Syntax:-
class BaseClass:
Body of base class
class DerivedClass(BaseClass):
Body of derived class
Derived class inherits features from the base class, adding new features to
it. This results into re-usability of code.
Prog1:-
class Person:
def __init__(self, first, last):
self.firstname = first
self.lastname = last
def Name(self):
return self.firstname + " " + self.lastname
class Employee(Person):
def __init__(self, first, last, staffnum):
Person.__init__(self,first, last)
self.staffnumber = staffnum
def GetEmployee(self):
return self.Name() + ", " + self.staffnumber
x = Person("Marge", "Simpson")
y = Employee("Homer", "Simpson", "1007")
print(x.Name())
print(y.GetEmployee())
19
A class can be derived from more than one base classes in Python. This is
called multiple inheritance.
In multiple inheritance, the features of all the base classes are inherited into
the derived class. The syntax for multiple inheritance is similar to
single inheritance.
Syntax:-
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
Prog1:-
class Person:
#defining constructor
def __init__(self, personName, personAge):
self.name = personName
self.age = personAge
#defining class methods
def showName(self):
print(self.name)
def showAge(self):
print(self.age)
#end of class definition
21
print ('Weeping...' )
d=BabyDog()
d.eat()
d.bark()
d.weep()
Deriving a class from other derived classes that are in turn derived from the
base class is called multi-path inheritance or hybrid inheritance.
1.8.Polymorphism
Polymorphism is made by two words "poly" and "morphs". Poly means many
and Morphs means form, shape. It defines that one task can be performed in
different ways. For example: You have a class animal and all animals talk.
But they talk differently. Here, the "talk" behavior is polymorphic in the
sense and totally depends on the animal. So, the abstract "animal" concept
does not actually "talk", but specific animals (like dogs and cats) have a
concrete implementation of the action "talk".
Example:-
22
a = "alfa"
b = (1, 2, 3, 4)
c = ['o', 'm', 'e', 'g', 'a']
print(a[2])
print(b[1])
print(c[3])
def fly(self):
print("Parrot can fly")
def swim(self):
print("Parrot can't swim")
class Penguin:
def fly(self):
print("Penguin can't fly")
def swim(self):
print("Penguin can swim")
# common interface
def flying_test(bird):
bird.fly()
#instantiate objects
blu = Parrot()
peggy = Penguin()
# passing the object
flying_test(blu)
flying_test(peggy)
1.9.Method Overloading
In Python we can define a method in such a way that there are multiple
ways to call it. Given a single method or function, we can specify the number
of parameters ourself. Depending on the function definition, it can be called
with zero, one, two or more parameters. This is known as method
23
overloading. Not all programming languages support method overloading,
but Python does.
Prog1:-
class Human:
def sayHello(self, name=None):
if name is not None:
print ('WELCOME TO ' + name)
else:
print ('Hello ')
# Create instance
obj = Human()
# Call the method
obj.sayHello()
# Call the method with a parameter
obj.sayHello('SUPREME')
1.10.Method Overriding
Override means having two methods with the same name but doing different
tasks. If there is any method in the superclass and a method with the same
name in a subclass, then by executing the method, the method of the
corresponding class will be executed.
Prog1:-
class Rectangle():
def __init__(self,length,breadth):
self.length = length
self.breadth = breadth
def getArea(self):
print (self.length*self.breadth," is area of rectangle")
class Square(Rectangle):
def __init__(self,side):
self.side = side
24
def getArea(self):
print (self.side*self.side," is area of square")
s = Square(4)
r = Rectangle(2,4)
s.getArea()
r.getArea()
1.11Encapsulation
Encapsulation is also the feature of object-oriented programming. It is used
to restrict access to methods and variables. In encapsulation, code and data
are wrapped together within a single unit from being modified by accident.
Example:-
class Computer:
def __init__(self):
self.__maxprice = 900
def sell(self):
print("Selling Price: {}".format(self.__maxprice))
def setMaxPrice(self, price):
self.__maxprice = price
c = Computer()
c.sell()
# change the price
c.__maxprice = 1000
c.sell()
# using setter function
c.setMaxPrice(1000)
c.sell()
In the above program, we defined a class Computer. We
use __init__() method to store the maximum selling price of computer. We
tried to modify the price. However, we can’t change it because Python treats
the __maxprice as private attributes. To change the value, we used a setter
function i.e setMaxPrice() which takes price as paramete
25
1.12Data Abstraction(Data Hiding)
Data abstraction and encapsulation both are often used as synonyms. Both
are nearly synonym because data abstraction is achieved through
encapsulation.
2.Exception
2.1.What is an Exception?
Exception can be said to be any abnormal condition in a program resulting to
the disruption in the flow of the program.
Whenever an exception occurs the program halts the execution and thus
further code is not executed. Thus exception is that error which python
script is unable to tackle with.
Exception in a code can also be handled. In case it is not handled, then the
code is not executed further and hence execution stops when exception
occurs.
26
3.Set up exception handling blocks
To use exception handling in Python, you first need to have a catch-all
except clause. The words "try" and "except" are Python keywords and are
used to catch exceptions.try-except [exception-name] blocks.The code
within the try clause will be executed statement by statement.
If an exception occurs, the rest of the try block will be skipped and the
except clause will be executed.
try:
some statements here
except:
exception handling
In addition to using an except block after the try block, you can also use the
finally block.
EXCEPTION PROGRAM
NAME AND
DESCRIPTION
Exception '2' + 2
Base class for all
exceptions
27
ArithmeticError try:
Base class for all errors a = 10/0
that occur for numeric print(a)
calculation. except ArithmeticError:
print ("This statement is
raising an arithmetic exception.")
else:
print ("Success.")
OverflowError i=1
Raised when a calculation try:
exceeds maximum limit f = 3.0**i
for a numeric type. for i in range(100):
print (i, f)
f = f ** 2
except OverflowError as err:
print ('Overflowed after ', f,
err)
ZeroDivisionError i=int(input("enter a number"))
Raised when division or
modulo by zero takes j=int(input("enter a number"))
place for all numeric
types. try:
k=i/j
print(j)
except ZeroDivisionError:
print('divided by zero')
print(c)
AttributeError x = [1, 2, 3]
Raised in case of failure x.next()
28
of attribute reference or x.next()
assignment. x.next()
x.next()
ImportError math.sqrt(5,2)
Raised when an import
statement fails.
KeyboardInterrupt i=int(input("enter a number"))
Raised when the user j=int(input("enter a number"))
interrupts program try:
execution, usually by k=i/j
pressing Ctrl+c. print(j)
except ZeroDivisionError:
print('divided by zero')
except KeyboardInterrupt:
print('keyboardinterrupt')
IndexError l=[0,1,1,2]
Raised when an index is print(l[5])
not found in a
sequence.
KeyError >>>a={'name':'sayon','age':35}
Raised when the >>>a[‘name’]
specified key is not >>>a[name1’]
found in the dictionary.
NameError anotherList = [4, 3, 5, 8, 1]
Raised when an
identifier is not found in
anather.append(4)
the local or global
namespace.
UnboundLocalError def f():
Raised when trying to x=x*2
access a local variable print(x)
in a function or method
but no value has been f()
assigned to it.
IOError name = "nope.txt"
Raised when an input/ with open(name) as f:
output operation fails, print(f.readline())
such as the print
statement or the open()
function when trying to
open a file that does not
exist.
SyntaxError print "hi"
29
Raised when there is an
error in Python syntax.
IndentationError
Raised when indentation
is not specified properly.
TypeError 10/'a'
Raised when an
operation or function is
attempted that is invalid
for the specified data
type.
ValueError num = int(input("Enter the
Raised when the built-in
number "))
function for a data type
has the valid type of re = 100/num
arguments, but the
arguments have invalid
values specified.
30
errors.
EnvironmentError
Base class for all exceptions
that occur outside the Python
environment.
SystemError
Raised when the interpreter
finds an internal problem, but
when this error is
encountered the Python
interpreter does not exit.
SystemExit
Raised when Python
interpreter is quit by using
the sys.exit() function. If not
handled in the code, causes
the interpreter to exit.
RuntimeError
Raised when a generated
error does not fall into any
category.
NotImplementedError
Raised when an abstract
method that needs to be
implemented in an inherited
class is not actually
implemented
Python allows to have multiple except blocks for a single try block.The block
which matches with the exception generated will get executed.
Prog1:-
class ExFile:
31
try:
num = int(input("Enter the number "))
re = 100/num
except ValueError :
print ("Value is not int type")
except ZeroDivisionError :
print ("Don't use zero" )
else:
print ("result is ",re)
5.Try ... except ... else clause:
The else clause in a try , except statement must follow all except clauses,
and is useful for code that must be executed if the try clause does not raise
an exception.
try:
data = something_that_can_go_wrong
except IOError:
handle_the_exception_error
else:
doing_different_exception_handling
Exceptions in the else clause are not handled by the preceding except
clauses.
Make sure that the else clause is run before the finally block.
Prog1:-
class ExFile:
i= int(input("Enter the number"))
j=int(input("Enter the number"))
try:
32
k=i/j
except ZeroDivisionError:
print('divided by zero')
else:
print('number is not divided by zero')
6. Try ... finally clause
The finally clause is optional. It is intended to define clean-up actions that
must be executed under all circumstances
A finally clause is always executed before leaving the try statement, whether
an exception has occurred or not.
class ExFile1:
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: can\'t find file or read data")
7.Raising an Exception(User Defined Exception)
We can raise an exception in our own program by using the raise exception
statement.Raising an exception breaks current code execution and returns
the exception back until it is handled.
try:
n=7
print(n)
raise ValueError
except:
print("Exception occurred")
33