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

Unit 1

The document discusses object-oriented programming concepts in Python including classes, objects, encapsulation, and inheritance. It defines classes as a way to create new types in Python and describes how classes can contain attributes (variables) and methods (functions). Objects are instances of a class that can access attributes and call methods. Encapsulation is used to restrict access to attributes and methods, making some private. Inheritance allows a child class to inherit attributes and methods from a parent class.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Unit 1

The document discusses object-oriented programming concepts in Python including classes, objects, encapsulation, and inheritance. It defines classes as a way to create new types in Python and describes how classes can contain attributes (variables) and methods (functions). Objects are instances of a class that can access attributes and call methods. Encapsulation is used to restrict access to attributes and methods, making some private. Inheritance allows a child class to inherit attributes and methods from a parent class.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 113

PYTHON APPLICATION

PROGRAMMING

Team Python

Department of Computer Science


and Engineering
PYTHON APPLICATION PROGRAMMING

Classes And Objects

Chitra G M
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Introduction
• Based on procedures
Procedure • Routines,subroutines,functio
ns
Oriented • Series of computational
Programming steps to be carried out
• Fortran,Algol,C,Cobol
• Based on Objects-interact
with real world
Object • properties and behaviors are
Oriented bundled into
Programming individual objects
• Java,C#,C++,Python
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Object(1)
• Python supports different kinds of data
For Ex:10,10.57,”python”,
[1,5,7,8,9],{“language1”:”Python”,”language2”:”c”}
•Each data is considered as an object and each object
has
•An object has a name that uniquely identifies it
•An object has a set of individual properties which make it
original, unique or outstanding
•An object is an instance of a type.
•An object has a set of abilities to perform specific
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Object(1)
• Python supports different kinds of data
For Ex:10,10.57,”python”,
[1,5,7,8,9],{“language1”:”Python”,”language2”:”c”}
•Each data is considered as an object and each object
has
•An object has a name that uniquely identifies it
•An object has a set of individual properties which make it
original, unique or outstanding
•An object is an instance of a type.
•An object has a set of abilities to perform specific
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Object(2)

There is a hint. Whenever you describe an object you use


a noun – to define the object's name
an adjective –to define the object's property
a verb - to define the object's activity
Example:
Snoopy is a fat dog which eats all day
Object name = Snoopy
Class = Dog
Property = Weight (fat)
Activity = Eat(all day)
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Object(3)
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes

•A language has only a few types namely strings,


numbers, lists, tuples, and dictionaries
•It can not provide all possible types we may want to have
•For example in real life we may want to create a type
called as employee,person,table,computer,dog etc
• A language should provide a mechanism to make our
own type
•This can be achieved through a feature called as class
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes

The simplest form of class definition looks like this

class ClassName:
<statement-1>
.
.
.
<statement-N>
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes

class student:
pass
print(student, type(student))

Output:
<class '__main__.student'> <class 'type'>

So, student is a type in the package


__main__.
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes
A class can have attributes(fields or variables)

class student: Output:


name="abc" abc
print(student.name)

A class can have functions(behaviour)


A class can have
class student:
behavior Output:
name="abc" student abc
def abc():
print(“student abc")
student.abc()
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes
Classes support two kinds of operations

Instantiation

Attribute
A class can have
References
behavior
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes
Creating a variables of a given type(student)is called
as instantiation

class student:
pass
a = student()
print(a, type(a))

Output:
<__main__.student object at 0x7fdb9d725e48>
<class '__main__.student'>
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes

•a = student() conceptually becomes student.__init__(a)

• The instance is passed as the frst argument to the

constructor.

• Even though the argument is implicit, in Python, we

require an explicit parameter

• This can be given any name - is normally called self


PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes
class abc:
def __init__(self):
print("constructor called")
print('self : ', self)
a = abc()
print('a : ', a)

Output:
constructor called
self : <__main__.abc object at 0x7f43d4e87860>
a : <__main__.abc object at 0x7f43d4e87860>
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes
• An object can have attributes

• Normally added and initialized in the constructor


•Attribute references use dot notation to access attributes
class Rect: with the class
associated
def __init__(self, l, b):
self.length = l
self.breadth = b
# print(length)
# error
# all names should be fully qualifed
print("__init__", self.length, self.breadth)
# initialize a Rect object r1 with length 20 and breadth
10
r1 = Rect(20, 10)
print(r1.length, r1.breadth)
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Classes

Output:
__init__ 20 10
20 10

• Attributes can be accessed any where with a fully


qualifed name
• Can create any number of objects
• Constructors are invoked to initialize them
There are 2 types of constructors namely

PYTHON FOR COMPUTATIONAL PROBLEM


SOLVING
Constructors
There are 2 types of constructors namely

Parameterized

Non-Parameterized
There are 2 types of constructors namely

PYTHON FOR COMPUTATIONAL PROBLEM


SOLVING
Constructors
Non - Parameterized Constructor
When no parameters are passed for invoking constructor

class Person: Output:


def __init__(self) without
print("without parameters
parameters")
p= Person()
There are 2 types of constructors namely

PYTHON FOR COMPUTATIONAL PROBLEM


SOLVING
Constructors
Parameterized Constructor
Parameters are passed for invoking the constructor

class Person:
def __init__(self,name,age):
self.name = name
self.age = age Output:
def display(self):
print(self.name,self.age) joe 30
p = Person("joe",30)
p.display()
Instance
There are 2variables
types of constructors namelyto each instance and class variables are for attributes and methods shared by all instances of the class.
are for data unique

PYTHON FOR COMPUTATIONAL PROBLEM


SOLVING
Class And Instance Variables
• Instance variables are for data unique to each instance
• Class variables are for attributes and methods shared by all
instances of the class.

class Animal:
kind = 'dog' # class variable shared by all instances
def __init__(self, name):
self.name = name # instance variable unique to each
instance
dog
a= Animal('pinky') pinky
b = Animal('snow') snow
print( a.kind ) # shared by all dogs
print( b.kind ) # shared by all dogs
print( a.name) # unique to a
print( b.name ) # unique to b
THANK YOU

Team Python*
Department of Computer Science and Engineerin

Contact Email ID’s:


[email protected]
PYTHON APPLICATION
PROGRAMMING

Team Python

Department of Computer Science


and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING

Encapsulation And Inheritance

Chitra G M
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Introduction
Fundamental Concepts Of OOP in Python

• B i n di n g t oge t h e r d a t a a n d
Encapsulation
functions

• Allows to define a class


that inherits all the methods
Inheritance
and properties from another
class
• Defines methods in the child
class that have the same
Polymorphism
name as the methods in the
parent class
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Encapsulation(1)

•Encapsulation is used to restrict access to methods and


variables
•In encapsulation, code and data are wrapped together
within a single unit
•It prevents data from direct modification
• Access modifiers are used to control access to class
resources.
For Example:public,private
•All members in a Python class are public by default.
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Encapsulation(1)

•The object of the same class is required to invoke a public


method.
• Private members of a class are denied access from the
environment outside the class.
• They can be handled only from within the class
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Encapsulation(3)

class Person:
def __init__(self,name,age): Output:
self.name = name shaun
self.age = age
p = Person("shaun",14)
print(p.name)

Add

Output:
p.name =
Vinay
"Vinay"
print(p.name)
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Encapsulation(3)
private attribute
•A double underscore __ is prefixed to a variable to make it
private
• It gives a strong suggestion not to touch it from outside the
class.class A:
def __init__(self,name,age):
•Any attempt to do so will result in an AttributeError
self.__name = name # Output:
private attribute AttributeError: 'A'
self.__age = age# private object has no
attribute attribute
x = A("Shaun",14) '__name'
print(x.__name)
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Encapsulation(3)
Getter and Setter methods
• getters are the methods which help access the private
attributes or get the value of the private attributes
• setters are the methods which help change or set the
value of private attributes
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Encapsulation(3)

class A:
def __init__(self,name =
"Shaun"):
self.__name = name
# make getter method Output:
def getname(self): Shaun
return self.__name joe
# make setter method
def setname(self,name):
self.__name = name
x = A()
print(x.getname())
x.setname("joe")
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(1)
•Powerful feature in object oriented programming
• Defines a class that inherits all the methods and
properties from another class.
•The new class is called derived (or child) class
•The one from which it inherits is called the base (or
parent) class.
• Derived class inherits features from the base class,
adding new features to it.
• Provides re-usability of code
•Inheritance establishes “is a” relationship between
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(2)
Syntax:
class Baseclass(Object):
body_of_base_class class
DerivedClass(BaseClass):
body_of_derived_class
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(3)

class A:
pass
Output:
class B(A):
True
pass
issubclass(B,A)

The function returns True if B is a subclass of


A,and False otherwise
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(4)
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.bark()
d.speak()

Output
dog barking
Animal Speaking
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(5)

class Base:
def __init__(self,subject):
self.subject= subject
def __str__(self):
return "The subject name is " + Output:
self.subject + "." The subject
class Derived(Base): name is Python
def __init__(self, name):
Base.__init__(self, name)
obj = Derived("Python")
print(obj)
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(5)

•When we create an object of the derived class, we


invoke the constructor of the derived class which in turn
calls the base class constructor on the base class sub
object.
• The base class provides a default implementation of the
behaviour for the derived class.
•The class defines the __str__() method, too, which makes
the class able to present its identity in clear text form.
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(6)-Instance Variables

class A1:
def __init__(self):
self.abc = 111
class B1(A1):
def __init__(self): Output:
super().__init__() 111
self.pqr = 222 222
obj = B1()
print(obj.abc)
print(obj.pqr)
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Inheritance(6)-Order to access an object’s entity

1. Inside the object itself


2. In all classes involved in the object's inheritance line
from bottom to top
3. If there is more than one class on a particular inheritance
path, Python scans them from left to right.

If it fails to find it in both the above mentioned things,


an exception called as AttributeError is raised
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
Overriding

To override a method in the base class, we must define a


new method with same name and same parameters in the
derived class
Example:
class A: #parent class
def display(self):
print ('This is base class.') Output:
class B(A): #derived class
def display(self): This is derived
print ('This is derived class.') class.
obj = B()
obj.display()
private attribute
The isinstance() function returns True if the specified object is of the specified type, otherwise False.
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an Attribu
PYTHON FOR COMPUTATIONAL PROBLEM
SOLVING
isinstance()

The isinstance() function returns True if the specified


object is of the specified type, otherwise False

class myObj:
name = "John" Output:
y = myObj() True
x = isinstance(y, myObj)
print(x)
THANK YOU

Team Python*
Department of Computer Science and Engineerin

Contact Email ID’s:


[email protected]
PYTHON APPLICATION
PROGRAMMING

Chitra G M
Computer Science and
Engineering
PYTHON APPLICATION PROGRAMMING

Introduction

Chitra G M
Department of Computer Science and Engineering
PYTHON APPLICATION PROGRAMMING
Design Pattern

What is a design pattern

• A design pattern in architecture and computer science is a


formal way of documenting a solution to a design problem in a
particular field of expertise.

• The idea was introduced by the architect Christopher


Alexander in the field of architecture and has been adapted for
various other disciplines, including computer science.
PYTHON APPLICATION PROGRAMMING
Design pattern

An organized collection of design patterns that relate to a


particular field is called a pattern language.

(wiki definition)
PYTHON APPLICATION PROGRAMMING
Design Pattern

Design Pattern Classifications

• Creational Patterns - They describe how best an object


can be created.
• A simple example of such design pattern is a singleton
class where only a single instance of a class can be
created. This design pattern can be used in situations
when we cannot have more than one instances of logger
logging application messages in a file.
PYTHON APPLICATION PROGRAMMING
Design Pattern

Design Pattern Classifications

• Structural Patterns – They describe how objects and


classes can work together to achieve larger results.
• A classic example of this would be the façade pattern
where a class acts as a façade in front of complex classes
and objects to present a simple interface to the client.
PYTHON APPLICATION PROGRAMMING
Design Pattern

Design Pattern Classifications

• Behavioral Patterns – They talk about interaction between


objects. Mediator design pattern, where an object of
mediator class, mediates the interaction of objects of
different classes to get the desired process working, is a
classical example of behavioral pattern.
PYTHON APPLICATION PROGRAMMING
Design Pattern

Singleton class

• Singleton pattern restricts the instantiation of a class


to one object.

• It is a type of creational pattern and involves only one


class to create methods and specified objects.

• It provides a global point of access to the instance


created.
PYTHON APPLICATION PROGRAMMING
Design Pattern

Singleton class Example


class single:
instance=None
def getinstance():
if single.instance==None:
single()
return single.instance
def __init__(self):
if single.instance!=None:
raise Exception("hey this is singleton")
else:
single.instance=self

s1=single()
print(s1)
THANK YOU

Chitra G M
Department of Computer Science and Engineering

[email protected]
+91 9900300411
PYTHON APPLICATION
PROGRAMMING

Chitra G M
Computer Science and
Engineering
PYTHON APPLICATION PROGRAMMING

Introduction

Chitra G M
Department of Computer Science and Engineering
PYTHON APPLICATION PROGRAMMING
Design Pattern

Facade

• A facade is an object that provides a simplified interface


to a larger body of code, such as a class library

Courtesy :Study.com
PYTHON APPLICATION PROGRAMMING
Design Pattern

Facade

• Façade pattern falls under the hood of Structural Design


Patterns.
• Façade is nothing but an interface that hides the inside details
and complexities of a system and provides a simplified ―front
end to the client.
• With façade pattern, client can work with the interface easily
and get the job done without being worried of the complex
operations being done by the system.

Courtesy :Study.com
PYTHON APPLICATION PROGRAMMING
Design pattern

Façade Example
PYTHON APPLICATION PROGRAMMING

Program

class ProcessingUnit:
'''Subsystem #1'''
def process(self):
print("Processing...")

class DisplayUnit:
'''Subsystem #2'‘’
def display(self):
print("Displaying...")

class Memory:
'''Subsystem #3'‘’
def ioOperation(self):
print("Reading and writing to memory...")
PYTHON APPLICATION PROGRAMMING

Program

class ProcessingUnit:
'''Subsystem #1'''
def process(self):
print("Processing...")

class DisplayUnit:
'''Subsystem #2'‘’
def display(self):
print("Displaying...")

class Memory:
'''Subsystem #3'‘’
def ioOperation(self):
print("Reading and writing to memory...")
PYTHON APPLICATION PROGRAMMING
Design Pattern

class Computer:
'''Facade'''
def __init__(self):
self.processingUnit = ProcessingUnit()
self.displayUnit = DisplayUnit()
self.memory = Memory()

def bootUp(self):
self.processingUnit.process()

self.memory.ioOperation()
self.displayUnit.display()
computer = Computer()
computer.bootUp()
THANK YOU

Chitra G M
Department of Computer Science and Engineering

[email protected]
+91 9900300411
PYTHON APPLICATION
PROGRAMMING

Chitra G M

Department of Computer Science


and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING

Exceptions

Chitra G M
Department of Computer Science and Engineering
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Introduction

• Error handling increases the robustness of your code, which


guards against potential failures that would cause your
program to exit in an uncontrolled fashion.

• Two basic types of errors can occur when running a python


program. They are
1. Syntax Errors
2. Exceptions
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Syntax error

• Syntax errors or parsing errors are errors that are due to


incorrect format of a python statement.

• These errors occur while the statement or program is being


translated to machine language and before it is being
executed.

• A component of python’s interpreter called as parser


discover these errors.
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Syntax error

Example

a=8
b = 10
c=ab Syntax Error :Invalid syntax
(3+4]

In the above snapshot we can observe that the error is due to


an incorrect syntax(format) of a python statement. These
errors occur before the execution of a statement.
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exceptions

• Even if a statement or expression is syntactically correct, it


may cause an error when an attempt is made to execute it.
Errors detected during execution are called exceptions and are
not unconditionally fatal.

• Hence, the exceptions should be properly handled so that an


abrupt termination of the program is prevented.
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exceptions Types

• The Exceptions fall into 2 categories namely


• Built-In exceptions
• User defined exceptions

Built-In exceptions
There are a number of exceptions which Python knows. We call
them built-in exceptions. The table below lists few of the built-in
exceptions.
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Built-in Exceptions

Exceptions Explanation
Keyboard Interrupt Raised when users hit Ctrl-C, the
interrupt key
Overflow Error Raised when a floating-point expression
evaluates to a value that is too large
ZeroDivision Error Raised when attempting to divide by 0
IO Error Raised when an I/O operation fails for an
I/O related reason
Index Error Raised when a sequence index is outside
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Built-in Exceptions Contd..

Name Error Raised when attempting to evaluate an


unassigned identifier
Type Error Raised when an operation or function is
applied to an object of the wrong type
Value Error Raised when an operation or function
has an argument of the right type but
incorrect value
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Built-in Exceptions Example

Exceptions Output
>>> 6/0 ZeroDivisionError: division by zero
>>> lst=[1,4,5] IndexError: list index out of range
>>> lst[3]
>>> a+10 NameError: name 'a' is not defined
>>> '2'*'6' TypeError: can't multiply sequence by
non-int of type 'str'
>>> int('3.5') ValueError: invalid literal for int() with
base 10: '3.5'

>>> 2.0**10000000 OverflowError: (34, 'Result too large')


private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Handling Exception

•It is not possible for a language to specify all possible unusual


cases. So the users can also specify exception as a class which
inherits from a class called exception.
•Python uses try and except keywords to handle exceptions.
Both keywords are followed by indented blocks.
Syntax

try :
#statements in try block
except :
#executed when error in try block
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
try, except blocks

The try: block contains one or more statements which are likely
to encounter an exception. If the statements in this block are
executed without an exception, the subsequent except: block is
skipped.

If the exception does occur, the program flow is transferred to


the except: block. The statements in the except: block are
meant to handle the cause of the exception appropriately.
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
try, except – example 1

try:
print(x)
except:
print("An exception occurred as x is not defined ")

Output:
An exception occurred as x is not defined
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
try, except – example -2

try: Name of exception after


y=1/0 the except keyword is
except ZeroDivisionError: given .
print("Python exception raised")

Output:
Python exception raised
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Multiple except clause

• There may be multiple except clauses with different exception


types in a single try block. If the type of exception doesn't
match any of the except blocks, it will remain unhandled and
the program will terminate

• It is always the first match and not the best match. The code
following the first match is executed. If no match occurs and
there is an default except block (with no exception specified),
then that block will be executed.
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Multiple except clause – example

try:
a=5
b=0
print (a/b)
except TypeError:
print('Unsupported operation')
except ZeroDivisionError:
print ('Division by zero not allowed')
print ('Out of try except blocks')

Output:
Division by zero not allowed
Out of try except blocks
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
else keyword in try – except block

• You can use the else keyword to define a block of code to be


executed if no errors were raised.
Example

try:
print("Hello") Output:
except: Hello
print("Something went wrong") Nothing went wrong
else:
print("Nothing went wrong")
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Raising exception

• Python also provides the raise keyword to be used in the


context of exception handling. It causes an exception to be
generated explicitly.
• Built-in errors are raised implicitly. However, a built-in or
custom exception can be forced during execution.
Syntax

raise Exception1name(<message>)

• This causes creation of an exception object with the message.


private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Raising exception – example 1

The raising of exception causes the program to abort if not in a try


block or transfer the control to the end of try block to match the
except blocks.

def Foo(number):
raise ZeroDivisionError Output:
try: An error occurred
Foo(0) terminate
except ArithmeticError:
print("An error occurred")
print("terminate")
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Raising exception – example 2

try:
x=int(input('Enter a number upto 100: '))
if x > 100:
raise ValueError(x)
except ValueError:
print(x, "is out of allowed range")
else:
print(x, "is within the allowed range")

Output: Output:
Enter a number upto 100: 45 Enter a number upto 100: 120
45 is within the allowed range 120 is out of allowed range
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Finally keyword in try except block

• This is an optional block which follows all the except blocks. It


is part of the try statement. This block shall be executed on
both normal flow and exceptional flow.

Let us understand the flow of execution.

i) Normal flow
try block – finally block if any – code following try block
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Finally keyword in try except block

ii) Exceptional flow


try block – exit the try block on an exception – find the first
matching except block – execute the matched except block – finally
block – code following try block

Syntax

try:
#statements in try block
except:
#executed when error in try block
finally:
#executed irrespective of exception occurred or not
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Finally keyword – example

def division(n):
try:
n=1/n Output:
except ZeroDivisionError: code is correct
print("Division failed") finally is executed
n = None 0.25
else: Division failed
print("code is correct")
finally:
print("finally is executed")
return n
print(division(4))
print(division(0))
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
User defined Exceptions

In Python, users can define custom exceptions by creating a new


class.

This exception class has to be derived, either directly or indirectly,


from the built-in Exception class.

Most of the built-in exceptions are also derived from this class.
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
User defined Exceptions – example

class MyException(Exception):
def __init__(self, str): Output: When
self.str = str 1<=n<=100
def __str__(self): enter a number:5
return self.str number is fine : 5
n = int(input("enter a number:")) thats all
try:
if not 1 <= n <= 100 :
raise MyException("number Output: When n>=100
not in range") enter a number:105
print("number is fine : ", n) number not in range
except MyException as e: thats all
print(e)
print("thats all")
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception propagation

• We say that a try block has dynamic scope. Any exception


raised in the block or any function called from there are
considered part of the try block.
• Any exception raised within these functions called from there
will cause the control to be propagated backwards to the
except blocks of this try block.
• If an exception is raised inside a function, it can be handled in
two ways
1. Inside the function
2. Outside the function
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception propagation – example 1

def mathOp(n):
try: Output: When n=0
return 1 / n Division not possible
except ArithmeticError: successfully completed
print("Division not possible")
return None
Output: When n=10
mathOp(0) successfully completed
mathOp(10)
print("successfully completed")
private attribute
A double underscore __ is prefixed to a variable to make it private. It gives a strong suggestion not to touch it from outside the class. Any attempt to do so will result in an AttributeError:
PYTHON FOR COMPUTATIONAL PROBLEM SOLVING
Exception propagation – example 2

def mathOp(x): Output: When n=0


return 1 / x An exception is raised
try: Exception Programming
mathOp(0)
except ArithmeticError:
print("An exception is raised") Output: When n=10
print("Exception Programming") Exception Programming
THANK YOU

Team Python*
Department of Computer Science and Engineering

Contact Email ID’s:


[email protected]
PYTHON APPLICATION
PROGRAMMING

Prof. Shilpa S
Assistant Professor

Department of Computer Science and Engineering


Contact Email id: [email protected]
PYTHON APPLICATION PROGRAMMING

Iterators, Generators, Closures, Callback,


Memoization and Composition

Prof. Shilpa S
Department of Computer Science and Engineering
PYTHON APPLICATION PROGRAMMING
Iterators

• An iterator in Python is an object that is used to iterate over iterable objects


like lists, tuples, dicts, and sets.
• The Python iterators object is initialized using the iter() method.
• It uses the next() method for iteration.
• __iter__(): The iter() method is called for the initialization of an iterator.
This returns an iterator object
• __next__(): The next method returns the next value for the iterable.
PYTHON APPLICATION PROGRAMMING
Iterators

Example:
string = “PYTHON"
ch= iter(string)
Output:
print(next(ch)) P
print(next(ch)) Y
print(next(ch)) T
print(next(ch)) H
print(next(ch)) O
print(next(ch)) N
PYTHON APPLICATION PROGRAMMING
Iterable vs Iterator

• Python iterable and Python iterator are different.


• The main difference between them is, iterable in Python cannot save the state of
the iteration, whereas in iterators the state of the current iteration gets saved.
• Note: Every iterator is also an iterable, but not every iterable is an iterator in
Python.
• Iterable is an object, that one can iterate over. It generates an Iterator when
passed to iter() method. An iterator is an object, which is used to iterate over an
iterable object using the __next__() method. Iterators have the __next__()
method, which returns the next item of the object.
PYTHON APPLICATION PROGRAMMING
Iterable vs Iterator

Example:
#Function to check object is iterable or not
def it(ob):
34 is iterable : False
try:
iter(ob) [4, 5] is iterable : True
return True (4, 5) is iterable : True
except TypeError: {'a': 4} is iterable : True
return False
dfsdf is iterable : True
for i in [34, [4, 5], (4, 5),{"a":4}, "dfsdf", 4.5]:
print(i,"is iterable :",it(i)) 4.5 is iterable : False
PYTHON APPLICATION PROGRAMMING
Generators

• A Generator in Python is a function that returns an iterator using the Yield


keyword.
• A generator function in Python is defined like a normal function, but whenever
it needs to generate a value, it does so with the yield keyword rather than
return.
• If the body of a def contains yield, the function automatically becomes a
Python generator function.
• The syntax is : def function_name():
yield statement
PYTHON APPLICATION PROGRAMMING
Generators :Example

def mygen(): • f is a generator object.


print("one") • A generator object is iterable.
yield 10
print("two") • So, we can call next on the iterable object.
yield 20 • When next(f) is called, the function mygen executes until and
print("three") inclusive of the yield statement.
yield 30
print("four") Output:
f = mygen() one
res = next(f) 10
print(res) two
res = next(f)
print(res)
20
res = next(f) three
print(res) 30
PYTHON APPLICATION PROGRAMMING
Generators
Observe the following about generators.
a) The generator function has one or more yields
b) The generator function as well the code calling next stay in some state of
execution simultaneously. This concept is called co-routine.
c) The generator function does not execute first time it is called – instead returns a
generator object.
d) The generator function resumes from where it had left of in the earlier execution
of call on the generator object
e) The generator objects are iterable
f) The generators are lazy –They do not produce all the results at a time.
PYTHON APPLICATION PROGRAMMING
Generators :Example

In this example, we will create two generators for Fibonacci Numbers, first a simple
generator and second generator using a for loop. def fib(limit):
a, b = 0, 1
0 while a < limit:
1 yield a
1 a, b = b, a + b
x = fib(5)
2
print(next(x))
3 print(next(x))
Using for in loop print(next(x))
0 print(next(x))
1 print(next(x))
1
print("\nUsing for in loop")
2 for i in fib(5):
3 print(i)
PYTHON APPLICATION PROGRAMMING
Closures

A function object that remembers values in enclosing scopes even when the
variable goes out of scope

Three characteristics of a Python closure are:


It is a nested function
It has access to a free variable in outer scope
It is returned from the enclosing function
PYTHON APPLICATION PROGRAMMING
Closures : Example

def outer(msg): # This is the outer enclosing function


def inner(): # This is the nested function
print(msg)
return inner # returns the nested function

# Now let's try calling this function.


different = outer("this is an example of closure")
different () #refers to inner()

Output:
this is an example of closure
PYTHON APPLICATION PROGRAMMING
Closures

• As observed from previous example code, closures help to invoke function


outside their scope

• The function print() has its scope only inside the print_msg. But with the use
of closures we can easily extend its scope to invoke a function outside its
scope
PYTHON APPLICATION PROGRAMMING
Closures

1. Example:
def f1(): #outer function Output:
def f2(): #inner function f2= 2908823806840
print ("Hello") Hello
print ("world") world
print('f2=',id(f2)) c= 2908823806840
return f2
c=f1() #refers to f2()
c()
print('c=',id(c)) #id of f2() and c() are same
PYTHON APPLICATION PROGRAMMING
Closures

2. Example:
def outerfunc(x):
Output:
def innerfunc():
7 49
print(x*x)
7 49
return innerfunc

myfunc=outerfunc(7)
myfunc() #refers to innerfunc()
del outerfunc
myfunc() #still refers to innerfunc() retaining the value of enclosing scope of x
PYTHON APPLICATION PROGRAMMING
Callback

• A function passed into another function as an argument, which is then


invoked inside the outer function to complete some kind of task.
Advantages:
• Calling function(outer function) can call the callback function as many times
as it required to complete the specified task
• Calling function can pass appropriate parameters according to the task to
the called functions. This allows information hiding
PYTHON APPLICATION PROGRAMMING
Callback : Example1

def fun1():
print("Within fun1")
def fun2():
print("Within fun2") Within fun1
def outer(x): Within fun2
x()
outer(fun1)
outer(fun2)
PYTHON APPLICATION PROGRAMMING
Callback : Example2
def fun1():
a,b = 12,45
sum = a+b
57
print(sum)
Within fun1
print("Within fun1")
5
def fun2(p,q):
Within fun2
div = p//q
print(div)
print("Within fun2")
def outer(x,y):
v1,v2 = 25,5
x()
y(v1,v2)
outer(fun1,fun2)
PYTHON APPLICATION PROGRAMMING
Callback : Example3
def fun1(*a):
sum = a[0]+a[1]+a[2]//a[0]-a[1]
print(sum) 25
print("Within fun1") Within fun1
def fun2(*p): 120
div = p[0]*p[1]*p[2]*p[3] Within fun2
print(div)
print("Within fun2")
def outer(x,*v1):
x(*v1)
outer(fun1,23,45,67)
outer(fun2,5,2,3,4)
PYTHON APPLICATION PROGRAMMING
Memoization

• Memoization is a technique of recording the intermediate results so that it


can be used to avoid repeated calculations and speed up the programs.
• It can be used to optimize the programs that use recursion.
• In Python, memoization can be done with the help of function decorators.
• @function_name decorator, which gives you the ability to cache the result of
your functions using the Least Recently Used (LRU) strategy.
PYTHON APPLICATION PROGRAMMING
Memoization

# Factorial program with memoization using decorators.


# A decorator function for function 'f' passed as parameter

memory = {}
def memoize_factorial(f):
# This inner function has access to memory and 'f'
def inner(num):
if num not in memory:
memory[num] = f(num)
print('result saved in memory')
else:
print('returning result from saved memory')
return memory[num]
return inner
PYTHON APPLICATION PROGRAMMING
Memoization

@memoize_factorial result saved in memory


result saved in memory
def facto(num):
result saved in memory
if num == 1: result saved in memory
return 1 result saved in memory
else: 120
return num * facto(num-1) returning result from saved
memory
120
print(facto(5))
print(facto(5)) # directly coming from saved memory
THANK YOU

Prof. Shilpa S
Assistant Professor

Department of Computer Science and Engineering


Contact Email id: [email protected]

You might also like