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

Python Programming - Unit 4 (1)

This document outlines a Python programming course focused on exceptions, input/output, and object-oriented programming. It covers fundamental concepts such as error handling, data streams, and class interface techniques, aiming to equip students with the skills to develop their own Python packages. The course is designed for individuals with moderate computer experience and has no prerequisites, covering Python 3 extensively.

Uploaded by

nehanixon33
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Programming - Unit 4 (1)

This document outlines a Python programming course focused on exceptions, input/output, and object-oriented programming. It covers fundamental concepts such as error handling, data streams, and class interface techniques, aiming to equip students with the skills to develop their own Python packages. The course is designed for individuals with moderate computer experience and has no prerequisites, covering Python 3 extensively.

Uploaded by

nehanixon33
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 208

UNIT-IV PYTHON FOR

PROGRAMMING AND
Exceptions, I/O and OOP PRODUCT DEVELOPMENT

© Kalasalingam academy of research and education


Course Outline

CO 1
Course description
This course aims to teach everyone the core of
programming computers using Python. We cover
CO 2
python programming from basics to core. The course
has no pre-requisites and avoids all but the simplest
mathematics. Anyone with moderate computer
experience should be able to master the materials in
this course. This course will cover Python data types,
functions, control and looping constructs, regular
expressions, user interface modules and the data
analytic packages. Once a student completes this
CO 4. course, they will be ready to perform core python
problem solving and also develop their own python
packages. This course covers Python 3.

CO 5.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Syllabus
Errors and Run time errors EXCEPTION,I/O & OOP
Exception Handling
Outcomes
Data streams-Input and Output
Create python programs to handle file I/O and exceptions,
Object Oriented Programming and solve problems with Object Oriented Concepts
Class Interface Techniques

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Unit 2 Outline

Lesson 1. Errors and Run time Errors


Lesson 1.Errors and Run time Errors

Lesson 2. Exception Handling

Lesson 3. Data Stream-Input and Output

Lesson 4. Object Oriented Programming

Lesson 5. Class Interface Techniques

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Course Progress

Lesson 1. Errors and Run time Errors

Lesson 2. Exception Handling

Lesson 3. Data Streams-Input and Output

Lesson 4. Object Oriented Programming

Lesson 5. Class Interface Techniques

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Topic 1
Exception Handling Introduction

Topic 2
Errors and Exception

Topic 3
Error Types

Topic 4
Exception Handling

First Lesson Outline

We will be learning about Exception Handling

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Exception Handling 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.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Errors and an Exception

•Errors cannot be handled, while Python exceptions can be handled at the run time.

•An error can be a syntax (parsing) error, while there can be many types of exceptions that could occur
during the execution and are not unconditionally inoperable.
•An Error might indicate critical problems that a reasonable application should not try to catch.

•An Exception might indicate conditions that an application should try to catch.

•Errors are a form of an unchecked exception and are irrecoverable like an OutOfMemoryError, which a
programmer should not try to handle.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Error Types

•Syntax Error

•Out of Memory Error

•Recursion Error

•Exceptions

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Syntax Error

Syntax errors often called as parsing errors, are predominantly caused when the parser detects a syntactic
issue in your code.

Syntax Error

The above red mark indicates when the parser ran into an error while executing the code. The token
preceding the red mark causes the failure. To rectify such fundamental errors, Python will do most of your
job since it will print for you the file name and the line number at which the error occurred.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Out of Memory Error

•Memory errors are mostly dependent on your systems RAM and are related to Heap.

•If you have large objects (or) referenced objects in memory, then you will see OutofMemoryError
(Source). It can be caused due to various reasons:
• Using a 32-bit Python Architecture (Maximum Memory Allocation given is very low, between 2GB - 4GB).
• Loading a very large data file
• Running a Machine Learning/Deep Learning model and many more.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Recursion Error

•It is related to stack and occurs when you call functions.

•As the name suggests, recursion error transpires when too many methods, one inside another is executed
(one with an infinite recursion), which is limited by the size of the stack.

Recursion
Error

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Indentation error

•Indentation error is similar in spirit to the syntax error and falls under it.

•However, specific to the only indentation related issues in the script.

Indentation
Error

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Course Progress

Lesson 1. Errors and Run time Errors

Lesson 2. Exception Handling

Lesson 3. Data Streams-Input and Output

Lesson 4. Object Oriented Programming

Lesson 5. Object Oriented Programming

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Exceptions

Even if the syntax of a statement or expression is correct, it may still cause an error when executed.
Python exceptions are errors that are detected during execution and are not unconditionally fatal.

An exception object is created when a Python script raises an exception.


If the script explicitly doesn't handle the exception, the program will be forced to terminate abruptly.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Exception Handling

•When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

•These exceptions can be handled using the try statement

•The try block lets you test a block of code for errors.

•The except block lets you handle the error.

•The finally block lets you execute code, regardless of the result of the try- and except blocks.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Exception Handling Example-1

output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Exception Handling Example-2

amount = 10000

# check that You are eligible to


# purchase Dsa Self Paced or not
if(amount>2999)
print("You are eligible to purchase Dsa Self Paced")

output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Exception Handling Example-3

marks = 10000

# perform division with 0


a = marks / 0
print(a)

output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Exception Handling Example-4
a = [1, 2, 3]
try:
print "Second element = %d" %(a[1])

# Throws error since there are only 3 elements in array


print "Fourth element = %d" %(a[3])

except IndexError:
print "An error occurred"

output

Second element = 2
An error occurred

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Exception Handling Example-5
try :
a=3
if a < 4 :
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print "Value of b = ", b

# note that braces () are necessary here for multiple exceptions


except(ZeroDivisionError, NameError):
print "\nError Occurred and Handled"

output

Error Occurred and Handled

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Exception Handling Example-6
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print "a/b result in 0"
else:
print c
# Driver program to test above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

output

-5.0
a/b result in 0

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Exception Handling Example-7

try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


except ZeroDivisionError:
print("Can't divide by zero")

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed’)

output

Can't divide by zero


This is always executed

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Exception Handling Example-8

try:
raise NameError("Hi there") # Raise Error
except NameError:
print "An exception"
raise # To determine whether the exception was raised or not

output

Traceback (most recent call last):


File "003dff3d748c75816b7f849be98b91b8.py", line 4, in
raise NameError("Hi there") # Raise Error
NameError: Hi there

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

data = 50
try:
data = data/0
except ZeroDivisionError:
print('Cannot divide by 0 ', end = '')
else:
print('Division successful ', end = '')
try:
data = data/5
except:
print('Inside except block ', end = '')
else:
print('GFG', end = ‘’)
output

Cannot divide by 0 GFG

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

data = 50
try:
data = data/10
except ZeroDivisionError:
print('Cannot divide by 0 ', end = '')
finally:
print('GeeksforGeeks ', end = '')
else:
print('Division successful ', end = ‘’)

output

Runtime error

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

value = [1, 2, 3, 4]
data = 0
try:
data = value[4]
except IndexError:
print('GFG', end = '')
except:
print('GeeksforGeeks ', end = ‘’)

output

GFG

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)
value = [1, 2, 3, 4]
data = 0
try:
data = value[3]
except IndexError:
print('GFG IndexError ', end = '')
except:
print('GeeksforGeeks IndexError ', end = '')
finally:
print('Geeks IndexError ', end = '')
data = 10
try:
data = data/0
except ZeroDivisionError:
print('GFG ZeroDivisionError ', end = '')
finally:
print('Geeks ZeroDivisionError ‘
output

Geeks IndexError GFG ZeroDivisionError Geeks ZeroDivisionError


© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING
Practice Session-Exception Handling (Predict the Output)

value = [1, 2, 3, 4, 5]
try:
value = value[5]/0
except (IndexError, ZeroDivisionError):
print(‘Great ', end = '')
else:
print('GFG ', end = '')
finally:
print(‘Welcome ', end = ‘’)

output
Great Welcome

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

def foo():
try:
return 1
finally:
return 2
k = foo()
print(k)

output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

def foo():
try:
print(1)
finally:
print(2)
foo()

output

12

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

def f(x):
yield x+1
g=f(8)
print(next(g))

output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

try:
if '1' != 1:
raise "someError"
else:
print("someError has not occurred")
except "someError":
print ("someError has occurre d")

output

invalid code

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

def f(x):
yield x+1
print("test")
yield x+2
g=f(9)

output
No output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

def f(x):
yield x+1
print("test")
yield x+2
g=f(10)
print(next(g))
print(next(g))

output

11 test 12

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

def a():
try:
f(x, 4)
finally:
print('after f')
print('after f?')
a()

output

error

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

def f(x):
for i in range(5):
yield i
g=f(8)
print(list(g))

output

[0, 1, 2, 3, 4]

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

g = (i for i in range(5))
type(g)

output
class <’generator’>

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

a=False
while not a:
try:
f_n = input("Enter file name")
i_f = open(f_n, 'r')
except:
print("Input file not found")

output

No error

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

lst = [1, 2, 3] lst[3]

output

IndexError

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

4 + ‘3’ if the time module has already been imported?

output

TypeError

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

int('65.43')

output

ValueError

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

def getMonth(m):
if m<1 or m>12:
raise ValueError("Invalid")
print(m)
getMonth(6)

output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Exception Handling (Predict the Output)

valid = False
while not valid:
try:
n=int(input("Enter a number"))
while n%2==0:
print("Bye")
valid = True
except ValueError:
print("Invalid")

output

Bye (printed infinite number of times)

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Lesson Summary

❑Error handling increases the robustness of your code, which guards against potential failures that would
cause your program to exit in an uncontrolled fashion.
❑ Errors cannot be handled, while Python exceptions can be handled at the run time.

❑ Recursion error is is related to stack and occurs when you call functions.

❑ Indentation error is similar in spirit to the syntax error and falls under it.

❑ When an error occurs, or exception as we call it, Python will normally stop and generate an error
message.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Course Progress

Lesson 1. Errors and Run time Errors

Lesson 2. Exception Handling

Lesson 3. Data Streams-Input and Output

Lesson 4. Object Oriented Programming

Lesson 5. Class Interface Techniques

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Topic 1
Types – Text, Binary and Raw Third Lesson Outline
Topic 2
File Handling
We will be learning about the streams using io
Topic 3 package of python.
File Modes

Topic 4 Operations on files including read, write, access,


Deleting files & directories overwrite, delete will be comprehended

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Data streams – io Module

•The io module provides Python’s main facilities for dealing with various types of I/O.

•There are three main types of I/O: text I/O, binary I/O and raw I/O.

•These are generic categories, and various backing stores can be used for each of them.

•A concrete object belonging to any of these categories is called a file object. Other common terms are
stream and file-like object.
•Independent of its category, each concrete stream object will also have various capabilities: it can be read-
only, write-only, or read-write.
•It can also allow arbitrary random access (seeking forwards or backwards to any location), or only
sequential access (for example in the case of a socket or pipe)

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Data streams – io Module

•All streams are careful about the type of data you give to them. For example giving a str object to the
write() method of a binary stream will raise a TypeError.
•So will giving a bytes object to the write() method of a text stream.

•Changed in python version 3.3: Operations that used to raise IOError now raise OSError, since IOError
is now an alias of OSError

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Text I/O

•Text I/O expects and produces str objects. This means that whenever the backing store is natively made of
bytes (such as in the case of a file), encoding and decoding of data is made transparently as well as
optional translation of platform-specific newline characters.
•The easiest way to create a text stream is with open(), optionally specifying an encoding:

•In-memory text streams are also available as StringIO objects:

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Binary I/O

•Binary I/O (also called buffered I/O) expects bytes-like objects and produces bytes objects.

•No encoding, decoding, or newline translation is performed.

•This category of streams can be used for all kinds of non-text data, and also when manual control over the
handling of text data is desired.
•The easiest way to create a binary stream is with open() with 'b' in the mode string:

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Raw I/O

•Raw I/O (also called unbuffered I/O) is generally used as a low-level building-block for binary and text
streams;
•It is rarely useful to directly manipulate a raw stream from user code. Nevertheless, you can create a raw
stream by opening a file in binary mode with buffering disabled:

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


File Handling

•The key function for working with files in Python is the open() function.

•The open() function takes two parameters; filename, and mode.

•There are four different methods (modes) for opening a file:


▪ "r" - Read - Default value. Opens a file for reading, error if the file does not exist
▪ "a" - Append - Opens a file for appending, creates the file if it does not exist
▪ "w" - Write - Opens a file for writing, creates the file if it does not exist
▪ "x" - Create - Creates the specified file, returns an error if the file exists
•In addition you can specify if the file should be handled as binary or text mode
▪ "t" - Text - Default value. Text mode
▪ "b" - Binary - Binary mode (e.g. images)

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Read from a File

•To open the file, use the built-in open() function.

•The open() function returns a file object, which has a read() method for reading the content of the file:

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Read Only Parts of the File

•By default the read() method returns the whole text, but you can also specify how many characters you
want to return:

•Read one line of the file:

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Looping through the contents of a file

•By looping through the lines of the file, you can read the whole file, line by line:

•It is a good practice to always close the file when you are done with it.

•f.close() will close the file

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Write to a file

•To write to an existing file, you must add a parameter to the open() function:
▪ "a" - Append - will append to the end of the file
▪ "w" - Write - will overwrite any existing content

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Overwrite the file

•Open the file in “w” mode to overwrite the contents of the file

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Modes in File Creation

•To create a new file in Python, use the open() method, with one of the following parameters:
▪ "x" - Create - will create a file, returns an error if the file exist
▪ "a" - Append - will create a file if the specified file does not exist
▪ "w" - Write - will create a file if the specified file does not exist

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Delete a file

To delete a file, you must import the OS module, and run its os.remove() function

To avoid getting an error, you might want to check if the file exists before you try to delete it

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-1

fo = open("sample.txt", "wb")
print ("File Name: ", fo.name)

print ("Mode of Opening: ", fo.mode)


print ("Is Closed: ", fo.closed)
print ("Softspace flag : ", fo.softspace)

File Name: sample.txt


Mode of Opening: wb
Is Closed: False
Softspace flag: 0

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-2
with open('filename.txt') as f:

data = f.read()

# Iterate over the lines of the File

with open('filename.txt') as f:

for line in f :

print(line, end=' ')

# process the lines

with open('filename.txt' , 'wt') as f:


f.write ('hi there, this is a first line of file.\n')

f.write ('and another line.\n’)

hi there, this is a first line of file.

and another line

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-3

print
file1 = open("myfile.txt","w") file1.seek(0)
L = ["This is Delhi \n","This is Paris \n","This is London \n"] print "Output of Readline(9) function is "
# \n is placed to indicate EOL (End of Line) print file1.readline(9)
file1.write("Hello \n")
file1.seek(0)
file1.writelines(L)
file1.close() #to change file access modes
# readlines function
file1 = open("myfile.txt","r+") print "Output of Readlines function is "
print "Output of Read function is " print file1.readlines()
print file1.read() print
Print file1.close()
# seek(n) takes the file handle to the nth
# bite from the beginning. output
file1.seek(0)
print "Output of Readline function is " Output of Read function is
print file1.readline() Hello
print
This is Delhi
file1.seek(0)
This is Paris
# To show difference between read and readline
print "Output of Read(9) function is " This is London
print file1.read(9)

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-4

file1 = open("myfile.txt","w")
file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.close() output
# Append-adds at last
file1 = open("myfile.txt","a")#append mode
file1.write("Today \n")
Output of Readlines after appending
file1.close() ['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today
file1 = open("myfile.txt","r") \n']
print "Output of Readlines after appending"
print file1.readlines() Output of Readlines after writing
print ['Tomorrow \n']
file1.close()
# Write-Overwrites
file1 = open("myfile.txt","w")#write mode
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
print "Output of Readlines after writing"
print file1.readlines()
print
file1.close()

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Lesson Summary

❑ Python consists of three main types of I/O: text I/O, binary I/O and raw I/O.
❑ Independent of its category, each concrete stream object will also have various capabilities: it can be
read-only, write-only, or read-write.
❑ There are four different methods (modes) for opening a file: read 'r', append 'a', write 'w', create 'c'
❑ In addition you can specify if the file should be handled as binary 'b' or text 't' mode
❑ To delete a file, you must import the OS module, and run its os.remove() function

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-File Handling (Predict the Output)

f = None
for i in range (5):
with open("data.txt", "w") as f:
if i > 2:
break
print(f.closed)

output

True

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-File Handling (Predict the Output)

fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name

for index in range(5):


line = fo.next()
print "Line No %d - %s" % (index, line)

# Close opened file


fo.close()

output

Displays Output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-File Handling (Predict the Output)

import sys
sys.stdout.write(' Hello\n')
sys.stdout.write('Python\n’)

output

Hello Python

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-File Handling (Predict the Output)

fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
fo.flush()
fo.close()

output

Flushes the file when closing them

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-File Handling (Predict the Output)

fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
fo.flush()
fo.close()

output

Flushes the file when closing them

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Course Progress

Lesson 1. Errors and Run time Errors

Lesson 2. Exception Handling

Lesson 3. Data Streams-Input and Output

Lesson 4. Object Oriented Programming

Lesson 5. Class Interface Techniques

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Topic 1
Class

Topic 2
Object

Topic 3
Inheritance

Topic 4
Encapsulation

Topic 5
Polymorphism
Fourth Lesson Outline
We will be learning about Object Oriented
Programming

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Object Oriented Programming

Python is a multi-paradigm programming language. It supports different programming approaches.


One of the popular approaches to solve a programming problem is by creating objects. This is known as Object-
Oriented Programming (OOP).
An object has two characteristics:
attributes
Behavior
Let's take an example:
A parrot is an object, as it has the following properties:
• name, age, color as attributes
• singing, dancing as behavior

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Class

A class is a blueprint for the object.


We can think of class as a sketch of a student with labels. It contains all the details about the name,
registerno, addr etc. Based on these descriptions. Here, a student is an object.
The example for class of student can be :
Class Student
Name
Here the class keyword defined the empty class student. From that classes, we can create an instance.
An instance is a specific object created from a particular class.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Object

An object (instance) is an instantiation of a class. When class is defined, only the description for the object
is defined. Therefore, no memory or storage is allocated.
The example for object of parrot class can be:
Obj=student()
Here Obj is an object of class student

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example 1: Creating Class and Object in Python
class Student:
# class attribute
Dept = “CSE"
# instance attribute
def init (self, name, Regno):
self.name = name
self.Regno = Regno
# instantiate the Parrot class
aiml= Student("Blu", 10)
security = Student("Woo", 15)
# access the class attributes
print("Blu is a {}".format(blu. class .Dept)
print("Woo is also a {}".format(woo. class .Dept))
# access the instance attributes
print("{} is {} Regno".format( blu.name, blu.Regno)
print("{} is {} Regno".format( woo.name, woo.Regno)

output
Blu is a Student
Woo is also a Student
Blu regno is 10
Woo regno is 15

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Methods
class Parrot:
# instance attributes
def init (self, name, age):
self.name = name
self.age = age
# instance method
def sing(self, song):
return "{} sings {}".format(self.name, song)
def dance(self):
return "{} is now dancing".format(self.name)
# instantiate the object
blu = Parrot("Blu", 10)
# call our instance methods
print(blu.sing("'Happy'"))
print(blu.dance())

output
Blu sings 'Happy'
Blu is now dancing

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Inheritance

Inheritance is a way of creating a new class for using details of an existing class without modifying it. The
newly formed class is a derived class (or child class). Similarly, the existing class is a base class (or parent
class).

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example
# parent class
class Bird:
def init (self):
print("Bird is ready")
def whoisThis(self):
print("Bird")
def swim(self):
print("Swim faster")
# child class
class Penguin(Bird):
def init (self):
# call super() function
super(). init ()
print("Penguin is ready")
def whoisThis(self):
print("Penguin")
def run(self):
print("Run faster")
peggy = Penguin() output
peggy.whoisThis()
peggy.swim() Bird is ready
Penguin is ready
Penguin
Swim faster
Run faster

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Encapsulation

Using OOP in Python, we can restrict access to methods and variables. This prevents data from direct
modification which is called encapsulation.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Encapsulation-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()
output
Selling Price: 900
Selling Price: 900
Selling Price: 1000

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Polymorphism

Polymorphism is an ability (in OOP) to use a common interface for multiple forms (data types).
Suppose, we need to color a shape, there are multiple shape options (rectangle, square, circle). However
we could use the same method to color any shape. This concept is called Polymorphism.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Polymorphism-Example
class Parrot:
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)
output
Parrot can fly
Penguin can't fly

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Python Objects and Classes

Python is an object oriented programming language. Unlike procedure oriented programming, where the main
emphasis is on functions, object oriented programming stresses on objects.

An object is simply a collection of data (variables) and methods (functions) that act on those data. Similarly, a
class is a blueprint for that object.

We can think of class as a sketch (prototype) of a house. It contains all the details about the floors, doors,
windows etc. Based on these descriptions we build the house. House is the object.

As many houses can be made from a house's blueprint, we can create many objects from a class. An object is
also called an instance of a class and the process of creating this object is called instantiation.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Defining a Class in Python

Like function definitions begin with the def keyword in Python, class definitions begin with a class
keyword.
A class creates a new local namespace where all its attributes are defined. Attributes may be data or
functions.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example
class Person:
"This is a person class"
age = 10
def greet(self):
print('Hello')
# Output: 10
print(Person.age)
# Output: <function Person.greet>
print(Person.greet)
# Output: "This is a person class"
print(Person. doc )

output
10
<function Person.greet at >
This is a person class

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Creating an Object in Python

We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class. The procedure to create an
object is similar to a function call.
Syntax
Ram = Person()

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example
class Person:
"This is a person class"
age = 10

def greet(self):
print('Hello')
# create a new object of Person class
ram = Person()
# Output: <function Person.greet>
print(Person.greet)

# Output: <bound method Person.greet of < main .Person object>>


print(ram.greet)

# Calling object's greet() method


# Output: Hello
ram.greet()
output

<<bound method Person.greet of < main .Person object at 0x7fd288e9fa30>>


Hello

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Constructors in Python

Class functions that begin with double underscore are called special functions as they have special
meaning.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example
class ComplexNumber:
def init (self, r=0, i=0):
self.real = r
self.imag = i
def get_data(self):
print(f'{self.real}+{self.imag}j')
# Create a new ComplexNumber object
num1 = ComplexNumber(2, 3)
# Call get_data() method
# Output: 2+3j
num1.get_data()
# Create another ComplexNumber object
# and create a new attribute 'attr'
num2 = ComplexNumber(5)
num2.attr = 10
# Output: (5, 0, 10)
print((num2.real, num2.imag, num2.attr))
# but c1 object doesn't have attribute 'attr'
# AttributeError: 'ComplexNumber' object has no attribute 'attr'
print(num1.attr)
output
2+3j
(5, 0, 10)

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Deleting Attributes and Objects

>>> num1 = ComplexNumber(2,3)


>>> del num1.imag
>>> num1.get_data()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'imag'

>>> del ComplexNumber.get_data


>>> num1.get_data()
Traceback (most recent call last):
...
AttributeError: 'ComplexNumber' object has no attribute 'get_data'

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-1

class Test:
# A sample method
def fun(self):
print("Hello")
# Driver code
obj = Test()
obj.fun()
output

Hello

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-2

class Person:
# init method or constructor
def init (self, name):
self.name = name
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person(‘John')
p.say_hi()

output

Hello, my name is John

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-3
class CSStudent: class CSStudent:

# Class Variable
# Class Variable
stream = 'cse'
stream = 'cse'
# The init method or constructor
# The init method or constructor def init (self, roll):
def init (self, roll):
# Instance Variable
self.roll = roll
# Instance Variable
self.roll = roll # Adds an instance variable
def setAddress(self, address):
# Objects of CSStudent class self.address = address
a = CSStudent(101)
# Retrieves instance variable
b = CSStudent(102) def getAddress(self):
return self.address
print(a.stream) # prints "cse"
print(b.stream) # prints "cse" # Driver Code
print(a.roll) # prints 101 a = CSStudent(101)
a.setAddress(“Tamilnadu, India")
print(a.getAddress())
# Class variables can be accessed using class
# name also output
print(CSStudent.stream) # prints "cse
Tamilnadu India

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-4
class MyClass:
# Hidden member of MyClass
hiddenVariable = 0

# A member method that changes


# hiddenVariable
def add(self, increment):
self. hiddenVariable += increment
print (self. hiddenVariable)
# Driver code
myObject = MyClass()
myObject.add(2)
myObject.add(5)
2
7 output

Traceback (most recent call last):


File "filename.py", line 13, in
print (myObject. hiddenVariable)
AttributeError: MyClass instance has
no attribute ' hiddenVariable'

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-5
class Test:
def init (self, a, b):
self.a = a
self.b = b
def repr (self):
return "Test a:%s b:%s" % (self.a, self.b)

def str (self):


return "From str method of Test: a is %s," \
"b is %s" % (self.a, self.b)
# Driver Code
t = Test(1234, 5678)
print(t) # This calls str ()
print([t]) # This calls repr ()

output
From str method of Test: a is 1234,b is 5678
[Test a:1234 b:5678]

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-6
class Test:
def init (self, a, b):
self.a = a
self.b = b
def repr (self):
return "Test a:%s b:%s" % (self.a, self.b)
# Driver Code
t = Test(1234, 5678)
print(t)

output

Test a:1234 b:5678

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-7
class Test:
def init (self, a, b):
self.a = a
self.b = b

# Driver Code
t = Test(1234, 5678)
print(t)

output

< main .Test instance at 0x7fa079da6710>

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-8
class Person(object):
# Constructor
def init (self, name):
self.name = name
# To get name
def getName(self):
return self.name

# To check if this person is employee


def isEmployee(self):
return False
# Inherited or Sub class (Note Person in bracket)
class Employee(Person):
# Here we return true
def isEmployee(self):
return True
# Driver code
emp = Person(“emp1") # An Object of Person
print(emp.getName(), emp.isEmployee())
emp = Employee(“emp2") # An Object of Employee
print(emp.getName(), emp.isEmployee())

output
(‘emp1', False)
(‘emp2', True

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-9
class Base(object):
pass # Empty Class

class Derived(Base):
pass # Empty Class

# Driver Code
print(issubclass(Derived, Base))
print(issubclass(Base, Derived))

d = Derived()
b = Base()

# b is not an instance of Derived


print(isinstance(b, Derived))

# But d is an instance of Base


print(isinstance(d, Base))

output
True
False
False
True

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-10
class Base1(object):
def init (self):
self.str1 = "Geek1"
print "Base1"
class Base2(object):
def init (self):
self.str2 = "Geek2"
print "Base2"
class Derived(Base1, Base2):
def init (self):
# Calling constructors of Base1
# and Base2 classes
Base1. init (self)
Base2. init (self)
print "Derived"
def printStrs(self):
print(self.str1, self.str2)
ob = Derived()
ob.printStrs()

output
Base1
Base2
Derived
('Geek1', 'Geek2')

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-11
class Base(object):
# Constructor
def init (self, x):
self.x = x
class Derived(Base):
# Constructor
def init (self, x, y):
Base.x = x
self.y = y
def printXY(self):

# print(self.x, self.y) will also work


print(Base.x, self.y)
# Driver Code
d = Derived(10, 20)
d.printXY()

output
(10, 20)

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-12
class Base1(object):
def init (self):
self.str1 = “emp1"
print "Base1"
class Base2(object):
def init (self):
self.str2 = “emp2"
print "Base2"
class Derived(Base1, Base2):
def init (self):
# Calling constructors of Base1
# and Base2 classes
Base1. init (self)
Base2. init (self)
print "Derived"
def printStrs(self):
print(self.str1, self.str2)
ob = Derived()
ob.printStrs()

output
Base1
Base2
Derived
(‘emp1', ‘emp2')

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-13
Class Base(object):
# Constructor
def init (self, x):
self.x = x
class Derived(Base):
# Constructor
def init (self, x, y):

''' In Python 3.x, "super(). init (name)"


also works'''
super(Derived, self). init (x)
self.y = y
def printXY(self):
# Note that Base.x won't work here
# because super() is used in constructor
print(self.x, self.y)
# Driver Code
d = Derived(10, 20)
d.printXY()

output
(10, 20)

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-14
class X(object):
def init (self, a):
self.num = a
def doubleup(self):
self.num *= 2
class Y(X):
def init (self, a):
X. init (self, a)
def tripleup(self):
self.num *= 3
obj = Y(4)
print(obj.num)
obj.doubleup()
print(obj.num)
obj.tripleup()
print(obj.num)

output
4
8
24

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-15
class Person(object):
def init (self, name):
self.name = name
def getName(self):
return self.name
def isEmployee(self):
return False
# Inherited or Subclass (Note Person in bracket)
class Employee(Person):
def init (self, name, eid):
''' In Python 3.0+, "super(). init (name)"
also works'''
super(Employee, self). init (name)
self.empID = eid

def isEmployee(self):
return True

def getID(self):
return self.empID
# Driver code
emp = Employee(“emp1", "E101")
print(emp.getName(), emp.isEmployee(), emp.getID())

output
(‘emp1', True, 'E101')

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-16
class Person:
def init (self, name, age):
self.name = name
self.age = age
# a class method to create a Person object by birth year.
@classmethod
def fromBirthYear(cls, name, year):
return cls(name, date.today().year - year)

# a static method to check if a Person is adult or not.


@staticmethod
def isAdult(age):
return age > 18
person1 = Person('m', 21)
person2 = Person.fromBirthYear('m', 1996)
print (person1.age)
print (person2.age)
# print the result
print (Person.isAdult(22))

21 output
21
True

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

class Student:
def init (self,name,id):
self.name=name
self.id=id
print(self.id
)
std=Student("Simon",1)
std.id=2
print(std.id)

output

1
2

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

class A:
def init (self):
self.count=5
self.count=count+1
a=A()
print(a.count)

output
Error

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

class Book:
definit (self,author):
self.author=author
book1=Book("V.M.Shah")
book2=book1

output

id(book1) and id(book2) will have same value.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

class A:
def init (self,num):
num=3
self.num=num
def change(self):
self.num=7
a=A(5)
print(a.num)
a.change()
print(a.num)

output
3
7

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example: Armstrong Number

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Output:

Enter the Number:


1634

The Number is an Armstrong Number


Example: Palindrome

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Output:

Enter The number:


5665
It is a Plindrome Number
Example : Printing numbers in triangle pattern

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Output:

1
23
456
7 8 9 10
11 12 13 14 15
Example: Half Pyramid of Stars (*)

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Output:

*
**
***
****
*****
Example:Inverted Half Pyramid of Stars (*)

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Output:

*****
****
***
**
*
Example: Full Pyramid of Stars (*)

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Output:
Example:

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Output:
Practice Session-Object Oriented Concepts (Predict the Output)

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


output:
Practice Session-Object Oriented Concepts (Predict the Output)

>>> class A:
pass
>>> class B(A):
pass
>>> obj=B()
>>> isinstance(obj,A)

output

True

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

class A:
def init (self):
self. x = 1
class B(A):
def display(self):
print(self. x)
def main():
obj = B()
obj.display()
main()

output

Error, private class member can’t be accessed in a subclass

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

class A:
def init (self):
self._x = 5
class B(A):
def display(self):
print(self._x)
def main():
obj = B()
obj.display()
main()

output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

class A:
def init (self,x=3):
self._x = x
class B(A):
def init (self):
super(). init (5)
def display(self):
print(self._x)
def main():
obj = B()
obj.display()

main()

output
5

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

class A:
def test1(self):
print(" test of A called ")
class B(A):
def test(self):
print(" test of B called ")
class C(A):
def test(self):
print(" test of C called ")
class D(B,C):
def test2(self):
print(" test of D called ")
obj=D()
obj.test()
output
test of B called

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)
class A:
def test(self):
print("test of A called")
class B(A):
def test(self):
print("test of B called")
super().test()
class C(A):
def test(self):
print("test of C called")
super().test()
class D(B,C):
def test2(self):
print("test of D called")
obj=D()
obj.test()
output
test of B called
test of C called
test of A called
© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING
Practice Session-Object Oriented Concepts (Predict the Output)

class A:
def str (self):
return '1'
class B(A):
def init (self):
super(). init ()
class C(B):
def init (self):
super(). init ()
def main():
obj1 = B()
obj2 = A()
obj3 = C()
print(obj1, obj2,obj3)
main()

output
111

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

class Demo:
def init (self):
self.x = 1
def change(self):
self.x = 10
class Demo_derived(Demo):
def change(self):
self.x=self.x+1
return self.x
def main():
obj = Demo_derived()
print(obj.change())

main()

output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

class A:
def repr (self):
return "1"
class B(A):
def repr (self):
return "2"
class C(B):
def repr (self):
return "3"
o1 = A()
o2 = B()
o3 = C()
print(obj1, obj2, obj3)

output

123

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

output

30

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

class Demo:
def check(self):
return " Demo's check "
def display(self):
print(self.check())
class Demo_Derived(Demo):
def check(self):
return " Derived's check "
Demo().display()
Demo_Derived().display()

output

Demo’s check Derived’s check

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

class A:
def init (self):
self.multiply(15)
def multiply(self, i):
self.i = 4 * i;
class B(A):
def init (self):
super(). init ()
print(self.i)

def multiply(self, i):


self.i = 2 * i;
obj = B()

output

30

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

output

Demo’s check Demo’s chec

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

output

True

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

output

The program runs fine and 1 is printed

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

output

The program has an error because b is private and hence


can’t be printe

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

output

The program runs fine and 1 is printed

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

output

The program runs properly and prints 45

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

output

The program runs fine and 5 is printed

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

class student:
def init (self):
self.marks = 97
self. cgpa = 8.7
def display(self):
print(self.marks)
obj=student()
print(obj._student cgpa)

output

The program runs fine and 8.7 is printed

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Object Oriented Concepts (Predict the Output)

output

Error because the member shape is a protected member

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Course Progress

Lesson 1. Errors and Run time Errors

Lesson 2. Exception Handling

Lesson 3. Data Streams-Input and Output

Lesson 4. Object Oriented Programming

Lesson 5. Class Interface Techniques

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Topic 1
Python Interface Module

Topic 2
Abstract Super Class

Fifth Lesson Outline


We will be learning about Class Interface
Techniques

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Python-interface module

In object-oriented languages like Python, the interface is a collection of method signatures that should be
provided by the implementing class. Implementing an interface is a way of writing an organized code and
achieve abstraction.
In python, interface is defined using python class statements and is a subclass of interface.Interface which
is the parent interface for all interfaces.
Syntax :
class IMyInterface(zope.interface.Interface):
# methods and attributes

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example
import zope.interface
class MyInterface(zope.interface.Interface):
x = zope.interface.Attribute("foo")
def method1(self, x):
pass
def method2(self):
pass
print(type(MyInterface))
print(MyInterface. module )
print(MyInterface. name )

# get attribute
x = MyInterface['x']
print(x)
print(type(x))
output
<class zope.interface.interface.InterfaceClass>
main
MyInterface
<zope.interface.interface.Attribute object at 0x00000270A8C74358>
<class 'zope.interface.interface.Attribute'>

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Abstract Super Classes

An abstract class can be considered as a blueprint for other classes. It allows you to create a set of
methods that must be created within any child classes built from the abstract class.
A class which contains one or more abstract methods is called an abstract class. An abstract method is a
method that has a declaration but does not have an implementation. While we are designing large
functional units we use an abstract class. When we want to provide a common interface for different
implementations of a component, we use an abstract class.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program-1

from abc import ABC, abstractmethod class Dog(Animal):


class Animal(ABC):
def move(self):
def move(self): print("I can bark")
pass
class Lion(Animal):
class Human(Animal): def move(self):
print("I can roar")
def move(self):
print("I can walk and run") # Driver code
R = Human()
R.move()
class Snake(Animal):
K = Snake()
def move(self): K.move()
print("I can crawl")
R = Dog()
R.move()
output
K = Lion()
K.move() I can walk and run
I can crawl
I can bark
I can roar

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Implementation Through Subclassing :

By subclassing directly from the base, we can avoid the need to register the class explicitly. In this case,
the Python class management is used to recognize Plugin Implementation as implementing the abstract
Plugin Base.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Python-interface module

In object-oriented languages like Python, the interface is a collection of method signatures that should be
provided by the implementing class. Implementing an interface is a way of writing an organized code and
achieve abstraction.
In python, interface is defined using python class statements and is a subclass of interface.Interface which
is the parent interface for all interfaces.
Syntax :
class IMyInterface(zope.interface.Interface):
# methods and attributes

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example Program

import abc

class parent:
def geeks(self):
pass

class child(parent):
def geeks(self):
print("child class")

# Driver code
print( issubclass(child, parent))
print( isinstance(child(), parent))

output
True
True

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Concrete Methods in Abstract Base Classes :

Concrete classes contain only concrete (normal)methods whereas abstract classes may contain both
concrete methods and abstract methods. The concrete class provides an implementation of abstract
methods, the abstract base class can also provide an implementation by invoking the methods via super().

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example
import abc
from abc import ABC, abstractmethod
class R(ABC):
def rk(self):
print("Abstract Base Class")
class K(R):
def rk(self):
super().rk()
print("subclass ")
# Driver code
r = K()
r.rk()

output

Abstract Base Class


subclass
© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING
Abstract Properties

Abstract classes include attributes in addition to methods, you can require the attributes in concrete classes
by defining them with @abstractproperty.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Example
import abc
from abc import ABC, abstractmethod

class parent(ABC):
@abc.abstractproperty
def geeks(self):
return "parent class"
class child(parent):

@property
def geeks(self):
return "child class"
try:
r =parent()
print( r.geeks)
except Exception as err:
print (err)

r = child()
print (r.geeks).

output
Can't instantiate abstract class parent with abstract methods geeks
child class
© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING
Abstract Class Instantiation :

Abstract classes are incomplete because they have methods that have nobody. If python allows creating an
object for abstract classes then using that object if anyone calls the abstract method, but there is no actual
implementation to invoke.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Abstract Class Instantiation :
from abc import ABC,abstractmethod
class Animal(ABC):
@abstractmethod
def move(self):
pass
class Human(Animal):
def move(self):
print("I can walk and run")
class Snake(Animal):
def move(self):
print("I can crawl")
class Dog(Animal):
def move(self):
print("I can bark")

class Lion(Animal):
def move(self):
print("I can roar")
c=Animal()
output
Traceback (most recent call last):
File "/home/ffe4267d930f204512b7f501bb1bc489.py", line 19, in
c=Animal()
TypeError: Can't instantiate abstract class Animal with abstract methods move

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class test:
def init (self,a="Hello World"):
self.a=a

def display(self):
print(self.a)
obj=test()
obj.display(

output

“Hello World” is displayed

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class change:
def init (self, x, y, z):
self.a = x + y + z

x = change(1,2,3)
y = getattr(x, 'a')
setattr(x, 'a', y+1)
print(x.a)

output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class test:
def init (self,a):
self.a=a

def display(self):
print(self.a)
obj=test()
obj.display()

output

Error as one argument is required while creating the object

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class test:
def init (self):
self.variable = 'Old'
self.Change(self.variable)
def Change(self, var):
var = 'New'
obj=test()
print(obj.variable
)

output

‘Old’ is printed

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class fruits:
def init (self, price):
self.price = price
obj=fruits(50)

obj.quantity=10
obj.bags=2

print(obj.quantity+len(obj. dict ))

output
13

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class Demo:
def init (self):
pass

def test(self):
print( name )

obj = Demo()
obj.test()

output

main

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

def add(c,k):
c.test=c.test+1
k=k+1
class A:
def init (self):
self.test = 0
def main():
Count=A()
k=0
for i in range(0,25):
add(Count,k)
print("Count.test=", Count.test)
print("k =", k)
main()
output

Count.test=25 k=0

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

>>> class demo():


def repr (self):
return ' repr built-in function called'
def str (self):
return ' str built-in function called'
>>> s=demo()
>>> print(s)

output

str called

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

>>> class demo():


def repr (self):
return ' repr built-in function called'
def str (self):
return ' str built-in function called'
>>> s=demo()
>>> print(s)

output

str called

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class stud:
def init (self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display (self):
print("Roll no : ", self.roll_no, ", Grade: ", self.grade)
stud1 = stud(34, 'S')
stud1.age=7
print(hasattr(stud1, 'age’))

output

True

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class stud:
‘Base class for all students’
def init (self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display (self):
print("Roll no : ", self.roll_no, ", Grade: ", self.grade)
print(student. doc )

output

Base class for all students

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class stud:
‘Base class for all students’
def init (self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display (self):
print("Roll no : ", self.roll_no, ", Grade: ", self.grade)
print(student. doc )

output

Base class for all students

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class People():

def init (self, name):


self.name = name

def namePrint(self):
print("Name: " + self.name)

person1 = People("Sally")
person2 = People("Louise")
person1.namePrint()

output

Sally

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class People():

def init (self, name):


self.name = name

def namePrint(self):
print("Name: " + self.name)

person1 = People("Sally")
person2 = People("Louise")
person1.namePrint()

output
As we are not updating any values, 'self' is not needed in def namePrint(self):

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)
class Pokemon():
def init (self, name, type):
self.name = name
self.type = type
def stringPokemon(self):
print("Pokemon name is {} and type is {}".format(self.name, self.type))
class GrassType(Pokemon):
# overrides the stringPokemon() function on 'Pokemon' class
def stringPokemon(self):
print("Grass type pokemon name is {}".format(self.name))
poke1 = GrassType('Bulbasaur', 'Grass')
poke1.stringPokemon
poke1.stringPokemon()
poke2 = Pokemon('Charizard', 'Fire')
poke2.stringPokemon
poke2.stringPokemon()
output
Grass type pokemon name is Bulbasaur Pokemon name is Charizard and type is
Fire

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class Test:
def init (self):
self.x = 0
class Derived_Test(Test):
def init (self):
Test. init (self)
self.y = 1
def main():
b = Derived_Test()
print(b.x,b.y)
main()

output

01

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class A:
def init (self, x= 1):
self.x = x
class der(A):
def init (self,y = 2):
super(). init ()
self.y = y
def main():
obj = der()
print(obj.x, obj.y)
main(

output

12

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class A:
def one(self):
return self.two()

def two(self):
return 'A'

class B(A):
def two(self):
return 'B'
obj1=A()
obj2=B()
print(obj1.two(),obj2.two())

output

AB

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class A:
def init (self):
self. x = 1
class B(A):
def display(self):
print(self. x)
def main():
obj = B()
obj.display()
main()
output

Error,Private class member can’t accessed outside class

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class A:
def init (self):
self. x = 5
class B(A):
def display(self):
print(self. x)
def main():
obj = B()
obj.display()
main()
output

Error,Private class member can’t accessed outside class

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class A:
def init (self,x=3):
self._x = x
class B(A):
def init (self):
super(). init (5)
def display(self):
print(self._x)
def main():
obj = B()
obj.display()

output
5

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class A:
def test1(self):
print(" test of A called ")
class B(A):
def test(self):
print(" test of B called ")
class C(A):
def test(self):
print(" test of C called ")
class D(B,C):
def test2(self):
print(" test of D called ")
obj=D()
obj.test()
output

test of B called

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class A:
def test(self):
print("test of A called")
class B(A):
def test(self):
print("test of B called")
super().test()
class C(A):
def test(self):
print("test of C called")
super().test()
class D(B,C):
def test2(self):
print("test of D called")
obj=D()
obj.test(
output
test of B called
test of C called
test of A called

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class A:
def repr (self):
return "1"
class B(A):
def repr (self):
return "2"
class C(B):
def repr (self):
return "3"
o1 = A()
o2 = B()
o3 = C()
print(obj1, obj2, obj3)

output

123

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class A:
def init (self):
self.multiply(15)
print(self.i)

def multiply(self, i):


self.i = 4 * i;
class B(A):
def init (self):
super(). init ()

def multiply(self, i):


self.i = 2 * i;
obj = B()
output
30

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class Demo:
def check(self):
return " Demo's check "
def display(self):
print(self.check())
class Demo_Derived(Demo):
def check(self):
return " Derived's check "
Demo().display()
Demo_Derived().display()

output

Demo’s check Derived’s check

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class A:
def init (self):
self.multiply(15)
def multiply(self, i):
self.i = 4 * i;
class B(A):
def init (self):
super(). init ()
print(self.i)

def multiply(self, i):


self.i = 2 * i;
obj = B()

output
30

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class Demo:
def check(self):
return " Demo's check "
def display(self):
print(self.check())
class Demo_Derived(Demo):
def check(self):
return " Derived's check "
Demo().display()
Demo_Derived().display()

output

Demo’s check Demo’s check

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class A:
def init (self, x, y):
self.x = x
self.y = y
def str (self):
return 1
def eq (self, other):
return self.x * self.y == other. x * other.y
obj1 = A(5, 2)
obj2 = A(2, 5)
print(obj1 == obj2)

output

True

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class A:
def one(self):
return self.two()
def two(self):
return 'A'
class B(A):
def two(self):
return 'B'
obj2=B()
print(obj2.two()))

output
B

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class fruits:
def init (self):
self.price = 100
self. bags = 5
def display(self):
print(self. bags)
obj=fruits()
obj.display()

output

The program runs fine and 5 is printed

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class student:
def init (self):
self.marks = 97
self. cgpa = 8.7
def display(self):
print(self.marks)
obj=student()
print(obj._student cgpa)

output

The program runs fine and 8.7 is printed

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

class objects:
def init (self):
self.colour = None
self._shape = "Circle"

def display(self, s):


self._shape = s
obj=objects()
print(obj._objects_shape)

output

Error because the member shape is a protected member

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

x=10
y=8
assert x>y, 'X too small')

output

No Output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

def f(x):
yield x+1
g=f(8)
print(next(g))

output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

def f(x):
yield x+1
print("test")
yield x+2
g=f(9)

output

No Output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

def f(x):
yield x+1
print("test")
yield x+2
g=f(9)

output

No Output

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

def f(x):
yield x+1
print("test")
yield x+2
g=f(10)
print(next(g))
print(next(g))

output

11

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

def a():
try:
f(x, 4)
finally:
print('after f')
print('after f?')
a()

output

error

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

def f(x):
for i in range(5):
yield i
g=f(8)
print(list(g))

output

[0,1,2,3,4]

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

import itertools
l1=(1, 2, 3)
l2=[4, 5, 6]
l=itertools.chain(l1, l2)
print(next(l1))

output

Tuple object is not iterator

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Practice Session-Class and Object (Predict the Output)

g = (i for i in range(5))
type(g)

output

Class<‘generator’>

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Lesson Summary

❑ Understand the Object oriented Concepts

❑ Understand the Classes and Objects.

© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING


Thank You!
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere,
magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna.
© Kalasalingam academy of research and education INTRODUCTION TO PYTHON PROGRAMMING

You might also like