Advanced Python Programming Practical Manual

Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.

AJAY PASHANKAR

PROGRAM 1 Write a program to Python program to implement various file operations.

First you need to create a text file and keep it in same folder where you save your programs

Program:
fo=open("foo.txt","wb")
print("name of file:",fo.name)
print("closed or not:",fo.closed)
print("opening mode:",fo.mode)
print("softspace flag:",fo.softspace)

WRITE A PROGRAM TO READ AN ENTIRE TEXT FILE.


def file_read(fname):
txt=open(fname)
print(txt.read())
file_read('hello.txt')

WRITE A PROGRAM TO APPEND TEXT TO A FILE AND DISPLAY THE


www.profajaypashankar.com Page 1 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

TEXT.
def main():
f=open("hello.txt","a+")
f.write("welcome to lottery of 200 marks ")
f.close()
main()

WRITE A PROGRAM TO READ LAST N LINES OF A FILE.


import sys
import os
def file_read_from_tail(fname,lines):
bufsize=8192
fsize=os.stat(fname).st_size
iter=0
with open(fname) as f:
if bufsize>fsize:
bufsize=fsize-1
data=[]
while True:
iter +=1
f.seek(fsize-bufsize*iter)
data.extend(f.readlines())
if len(data)>= lines or f.tell()==0:
print("".join(data[-lines:]))
break

file_read_from_tail('README.txt',1)

www.profajaypashankar.com Page 2 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

PROGRAM 2 Write a program to Python program to demonstrate use of regular expression


for suitable application.

#pattern matching using Regular Expression

import re

pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)

if result:
print("Search successful.")
else:
print("Search unsuccessful.")

Tip: To build and test regular expressions, you can use RegEx tester tools such as regex101. This tool
not only helps you in creating regular expressions, but it also helps you learn it.
Now you understand the basics of RegEx, let's discuss how to use RegEx in your Python code.

Python RegEx
Python has a module named re to work with regular expressions. To use it, we need to import the
module.
import re
The module defines several functions and constants to work with RegEx.

re.findall()
The re.findall() method returns a list of strings containing all matches.

Example 1: re.findall()

# Program to extract numbers from a string

import re
www.profajaypashankar.com Page 3 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

string = 'hello 12 hi 89. Howdy 34'


pattern = '\d+'

result = re.findall(pattern, string)


print(result)

#Output:

If the pattern is not found, re.findall() returns an empty list.

re.split()
The re.split method splits the string where there is a match and returns a list of strings where the
splits have occurred.

Example 2: re.split()

import re

string = 'Twelve:12 Eighty nine:89.'


pattern = '\d+'

result = re.split(pattern, string)


print(result)

# Output:

If the pattern is not found, re.split() returns a list containing the original string.

You can pass maxsplit argument to the re.split() method. It's the maximum number of splits that will
occur.

import re
string = 'Twelve:12 Eighty nine:89 Nine:9.'
pattern = '\d+'

# maxsplit = 1
# split only at the first occurrence
result = re.split(pattern, string, 1)
print(result)

# Output:

www.profajaypashankar.com Page 4 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

By the way, the default value of maxsplit is 0; meaning all possible splits.

re.sub()
The syntax of re.sub() is:
re.sub(pattern, replace, string)
The method returns a string where matched occurrences are replaced with the content
of replace variable.

Example 3: re.sub()

# Program to remove all whitespaces


import re

# multiline string
string = 'abc 12\
de 23 \n f45 6'

# matches all whitespace characters


pattern = '\s+'

# empty string
replace = ''

new_string = re.sub(pattern, replace, string)


print(new_string)

# Output:

If the pattern is not found, re.sub() returns the original string.

You can pass count as a fourth parameter to the re.sub() method. If omited, it results to 0. This will
replace all occurrences.

import re

# multiline string
string = 'abc 12\
de 23 \n f45 6'

# matches all whitespace characters


pattern = '\s+'
replace = ''

new_string = re.sub(r'\s+', replace, string, 1)


print(new_string)

# Output:

www.profajaypashankar.com Page 5 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

re.subn()
The re.subn() is similar to re.sub() except it returns a tuple of 2 items containing the new string and
the number of substitutions made.

Example 4: re.subn()

# Program to remove all whitespaces


import re

# multiline string
string = 'abc 12\
de 23 \n f45 6'

# matches all whitespace characters


pattern = '\s+'

# empty string
replace = ''

new_string = re.subn(pattern, replace, string)


print(new_string)

# Output:

re.search()
The re.search() method takes two arguments: a pattern and a string. The method looks for the first
location where the RegEx pattern produces a match with the string.
If the search is successful, re.search() returns a match object; if not, it returns None.
match = re.search(pattern, str)

Example 5: re.search()

import re

string = "Python is fun"

# check if 'Python' is at the beginning


match = re.search('\APython', string)

if match:
print("pattern found inside the string")
else:
print("pattern not found")

# Output:

www.profajaypashankar.com Page 6 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

Here, match contains a match object.

Match object
You can get methods and attributes of a match object using dir() function.
Some of the commonly used methods and attributes of match objects are:

match.group()
The group() method returns the part of the string where there is a match.
Example 6: Match object

import re

string = '39801 356, 2102 1111'

# Three digit number followed by space followed by two digit number


pattern = '(\d{3}) (\d{2})'

# match variable contains a Match object.


match = re.search(pattern, string)

if match:
print(match.group())
else:
print("pattern not found")

# Output:

Here, match variable contains a match object.


Our pattern (\d{3}) (\d{2}) has two subgroups (\d{3}) and (\d{2}). You can get the part of the
string of these parenthesized subgroups. Here's how:
>>> match.group(1)
'801'

>>> match.group(2)
'35'
>>> match.group(1, 2)
('801', '35')

>>> match.groups()
('801', '35')

match.start(), match.end() and match.span()


The start() function returns the index of the start of the matched substring. Similarly, end() returns
the end index of the matched substring.
>>> match.start()
2
>>> match.end()
8
The span() function returns a tuple containing start and end index of the matched part.

www.profajaypashankar.com Page 7 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

>>> match.span()
(2, 8)

match.re and match.string


The re attribute of a matched object returns a regular expression object. Similarly, string attribute
returns the passed string.
>>> match.re
re.compile('(\\d{3}) (\\d{2})')

>>> match.string
'39801 356, 2102 1111'

Using r prefix before RegEx


When r or R prefix is used before a regular expression, it means raw string. For example, '\n' is a new
line whereas r'\n' means two characters: a backslash \ followed by n.
Backlash \ is used to escape various characters including all metacharacters. However, using r prefix
makes \ treat as a normal character.

Example 7: Raw string using r prefix

import re

string = '\n and \r are escape sequences.'

result = re.findall(r'[\n\r]', string)


print(result)

# Output:

-------------------------------------------------------------------------------------------------------------------
PROGRAM 3 Write a Program to demonstrate concept of threading and multitasking in
Python.

import threading # import the thread module


import time # import time module

def cal_sqre(num): # define the cal_sqre function


print(" Calculate the square root of the given number")
for n in num:
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(' Square is : ', n * n)

def cal_cube(num): # define the cal_cube() function


print(" Calculate the cube of the given number")
for n in num:
time.sleep(0.3) # at each iteration it waits for 0.3 time
print(" Cube is : ", n * n *n)

arr = [4, 5, 6, 7, 2] # given array

t1 = time.time() # get total time to execute the functions


cal_sqre(arr) # call cal_sqre() function
cal_cube(arr) # call cal_cube() function

print(" Total time taken by threads is :", time.time() - t1) # print the total time
www.profajaypashankar.com Page 8 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

output:

===============================================================

In the above output we can see error regarding thread module in python 3.1 And above
version thread module is obsolete or discarded use threading instead.

===============================================================

PROGRAM 4 Write a Python Program to work with databases in Python to perform


operations such as

a. Connecting to database

b. Creating and dropping tables

c. Inserting and updating into tables.

===========================================================

Before using any database with python program we need to install that
database connector for python here we have used mysql connector for
python for installation refer following link : https://youtu.be/uh3tub-zGDo
==================================================
import mysql.connector
db=mysql.connector.connect(user='root',passwd='12345',host='127.0.0.1',database
='nit')
#prepare a cursor object using cursor() method
cursor=db.cursor()
#drop table if it already exit using execute() method.
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# create table as per requirement
sql="""CREATE TABLE EMPLOYEE(FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR (20),
AGE INT,SEX CHAR(1),INCOME FLOAT)"""
cursor.execute(sql)
print("Table created Succesfully");
# disconnect from server
db.close()

www.profajaypashankar.com Page 9 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

Design a database application to that allows the user to add the records
import mysql.connector
db=mysql.connector.connect(user='root',passwd='root',host='127.0.0.1',database='n
it')
cursor=db.cursor()
sql="INSERT INTO EMPLOYEE(FIRST_NAME,\
LAST_NAME,AGE,SEX,INCOME)\
VALUES('%s','%s','%d','%c','%d')"%\
('Ajay','Moi',19,'M',22000)
try:
cursor.execute(sql)
print("Data Added Successfully")
db.commit()
except:
db.rollback()
db.close()

www.profajaypashankar.com Page 10 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

-----------------------------------------------------------------------------------------------
PROGRAM 5 Write a Python Program to demonstrate different types of exception handing.

import sys
randomList=['a',0,2]
for entry in randomList :
try:
print("the entry is ",entry)
r=1/int(entry)
break
except:
print("oops !",sys.exc_info()[0],"occured")
print("next entry")
print()
print("the reciprocal of",entry,"is",r)

www.profajaypashankar.com Page 11 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

-------------------------------------------------------------------------------------------------------------

PROGRAM 6 Write a GUI Program in Python to design application that demonstrates

a. Different fonts and colors

from tkinter import *

window=Tk()

lbl=Label(window, text="This is Label widget", fg='red', font=("Helvetica", 16))

lbl.place(x=60, y=50)

window.title('Hello Python')

window.geometry("300x200+10+10")

window.mainloop()

Change color and font face and size

lbl=Label(window, text="This is Label widget", fg='cyan', font=("Verdana", 18))

www.profajaypashankar.com Page 12 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

from tkinter import *

window=Tk()

btn=Button(window, text="This is Button widget", fg='blue')

btn.place(x=80, y=100)

lbl=Label(window, text="This is Label widget", fg='red', font=("Helvetica", 16))

lbl.place(x=60, y=50)

txtfld=Entry(window, text="This is Entry Widget", bd=5)

txtfld.place(x=80, y=150)

window.title('Hello Python')

window.geometry("300x200+10+10")

window.mainloop()

www.profajaypashankar.com Page 13 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

import tkinter

from tkinter import *

root=Tk()

O=Canvas(root,bg="blue",width=500,height=500)

O.pack()

n=Label(root,text="hello World")

n.pack()

root.mainloop()

b. Different Layout Managers

Pack layout

import tkinter as tk

root = tk.Tk()

w = tk.Label(root, text="Red Sun", bg="red", fg="white")

w.pack()

www.profajaypashankar.com Page 14 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

w = tk.Label(root, text="Green Grass", bg="green", fg="black")

w.pack()

w = tk.Label(root, text="Blue Sky", bg="blue", fg="white")

w.pack()

tk.mainloop()

-------------------------------------------------------------------------------------------------------------------

Place Layout:

import tkinter as tk
import random

root = tk.Tk()
# width x height + x_offset + y_offset:
root.geometry("170x200+30+30")

languages = ['Python','Perl','C++','Java','Tcl/Tk']
labels = range(5)
for i in range(5):
ct = [random.randrange(256) for x in range(3)]
brightness = int(round(0.299*ct[0] + 0.587*ct[1] + 0.114*ct[2]))
ct_hex = "%02x%02x%02x" % tuple(ct)
bg_colour = '#' + "".join(ct_hex)
l = tk.Label(root,
text=languages[i],
fg='White' if brightness < 120 else 'Black',
bg=bg_colour)
l.place(x = 20, y = 30 + i*30, width=120, height=25)

root.mainloop()

www.profajaypashankar.com Page 15 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

-----------------------------------------------------------------------------------------------------------------

Grid Layout

import tkinter as tk

colours = ['red','green','orange','white','yellow','blue']

r=0

for c in colours:

tk.Label(text=c, relief=tk.RIDGE, width=15).grid(row=r,column=0)

tk.Entry(bg=c, relief=tk.SUNKEN, width=10).grid(row=r,column=1)

r=r+1

tk.mainloop()

-------------------------------------------------------------------------------------------------------------------

c. Event Handling

from tkinter import *

class MyWindow:

def __init__(self, win):

self.lbl1=Label(win, text='First number')

www.profajaypashankar.com Page 16 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

self.lbl2=Label(win, text='Second number')

self.lbl3=Label(win, text='Result')

self.t1=Entry(bd=3)

self.t2=Entry()

self.t3=Entry()

self.btn1 = Button(win, text='Add')

self.btn2=Button(win, text='Subtract')

self.lbl1.place(x=100, y=50)

self.t1.place(x=200, y=50)

self.lbl2.place(x=100, y=100)

self.t2.place(x=200, y=100)

self.b1=Button(win, text='Add', command=self.add)

self.b2=Button(win, text='Subtract')

self.b2.bind('<Button-1>', self.sub)

self.b1.place(x=100, y=150)

self.b2.place(x=200, y=150)

self.lbl3.place(x=100, y=200)

self.t3.place(x=200, y=200)

def add(self):

self.t3.delete(0, 'end')

num1=int(self.t1.get())

num2=int(self.t2.get())

result=num1+num2

self.t3.insert(END, str(result))

def sub(self, event):

self.t3.delete(0, 'end')

num1=int(self.t1.get())

num2=int(self.t2.get())

result=num1-num2

self.t3.insert(END, str(result))

window=Tk()

mywin=MyWindow(window)

window.title('Hello Python')

www.profajaypashankar.com Page 17 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

window.geometry("400x300+10+10")

window.mainloop()

-------------------------------------------------------------------------------------------------------------------

7 Write Python Program to create application which uses date and time in Python.

# Import the libraries

from tkinter import *

from tkinter.ttk import *

# importing strftime function to

# retrieve system's time

from time import strftime

# creating tkinter window

root = Tk()

root.title('Clock')

from tkinter import *

import datetime as dt

def time():

string = strftime('%H:%M:%S %p')

www.profajaypashankar.com Page 18 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

lbl.config(text=string)

lbl.after(1000, time)

# Styling the label widget so that clock

# will look more attractive

lbl = Label(root, font=('calibri', 40, 'bold'),background='purple',foreground='white')

# Placing clock at the centre

# of the tkinter window

lbl.pack(anchor='center')

time()

mainloop()

def date():

# Create an instance of tkinter

win = Tk()

win.title("Display Current Date")

win.geometry("700x350")

date = dt.datetime.now()

# Create Label to display the Date

label = Label(win, text=f"{date:%A, %B %d, %Y}", font="Calibri, 20")

label.pack(pady=20)

date()

mainloop()

www.profajaypashankar.com Page 19 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

-------------------------------------------------------------------------------------------------------------------

8 Write a Python program to create server-client and exchange basic information.

#socket_server.py

import socket
def server_program():
# get the hostname
host = socket.gethostname()
port = 5000 # initiate port no above 1024

server_socket = socket.socket() # get instance


# look closely. The bind() function takes tuple as argument
server_socket.bind((host,port)) # bind host address and port together

# configure how many client the server can listen simultaneously


server_socket.listen(2)
conn, address = server_socket.accept() # accept new connection
print("Connection from: " + str(address))
while True:
# receive data stream. it won't accept data packet greater than 1024 bytes
data = conn.recv(1024).decode()
if not data:
# if data is not received break
break
print("from connected user: " + str(data))
data = input(' -> ')
conn.send(data.encode()) # send data to the client

conn.close() # close the connection

if __name__ == '__main__':
server_program()
------------------------------------------------------------------------------------------------------------
#socket_client.py
import socket

def client_program():
host = socket.gethostname() # as both code is running on same pc
port = 5000 # socket server port number

client_socket = socket.socket() # instantiate


client_socket.connect((host,port)) # connect to the server

www.profajaypashankar.com Page 20 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

message = input(" -> ") # take input

while message.lower().strip() != 'bye':


client_socket.send(message.encode()) # send message
data = client_socket.recv(1024).decode() # receive response

print('Received from server: ' + data) # show in terminal

message = input(" -> ") # again take input

client_socket.close() # close the connection

if __name__ == '__main__':
client_program()

===============================================================
IMP NOTE:
1. Create 2 files namely socket_server.py and socket_client.py separately.
2. After successful compilation.
3. Open two different shell
4. First run socket_server.py
5. Then run socket_client.py
6. Now type something in socket_client.py
7. Then again write reply from server program.
8. At last, write bye from client program to terminate both program.

Socket_server.py shell

Socket_client.py shell

-------------------------------------------------------------------------------------------------------------------
9 Write a program to Python program to implement concepts of OOP such as

a. Types of Methods

class Dog:

# class attribute
attr1 = "mammal"

www.profajaypashankar.com Page 21 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

# Instance attribute
def __init__(self, name):
self.name = name

def speak(self):
print("My name is {}".format(self.name))

# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")

# Accessing class methods


Rodger.speak()
Tommy.speak()

b. Inheritance

# Python code to demonstrate how parent constructors


# are called.

# parent class
class Person(object):

# __init__ is known as the constructor


def __init__(self, name, idnumber):
self.name = name
self.idnumber = idnumber

def display(self):
print(self.name)
print(self.idnumber)

def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))

# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post

# invoking the __init__ of the parent class


Person.__init__(self, name, idnumber)

def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))

# creation of an object variable or an instance


a = Employee('james', 886012, 200000, "Intern")

# calling a function of the class Person using


www.profajaypashankar.com Page 22 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

# its instance
a.display()
a.details()

Output:

c. Polymorphism

class Bird:

def intro(self):
print("There are many types of birds.")

def flight(self):
print("Most of the birds can fly but some cannot.")

class sparrow(Bird):

def flight(self):
print("Sparrows can fly.")

class ostrich(Bird):

def flight(self):
print("Ostriches cannot fly.")

obj_bird = Bird()
obj_spr = sparrow()
obj_ost = ostrich()

obj_bird.intro()
obj_bird.flight()

obj_spr.intro()
obj_spr.flight()

obj_ost.intro()
obj_ost.flight()

OUTPUT:

------------------------------------------------------------------------------------------------------------------

www.profajaypashankar.com Page 23 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

10 Write a program to Python program to implement concepts of OOP such as

a. Abstract methods and classes

# Python program showing


# abstract base class work

from abc import ABC, abstractmethod

class Polygon(ABC):

@abstractmethod
def noofsides(self):
pass

class Triangle(Polygon):

# overriding abstract method


def noofsides(self):
print("I have 3 sides")

class Pentagon(Polygon):

# overriding abstract method


def noofsides(self):
print("I have 5 sides")

class Hexagon(Polygon):

# overriding abstract method


def noofsides(self):
print("I have 6 sides")

class Quadrilateral(Polygon):

# overriding abstract method


def noofsides(self):
print("I have 4 sides")

# Driver code
R = Triangle()
R.noofsides()

K = Quadrilateral()
K.noofsides()

R = Pentagon()
R.noofsides()

K = Hexagon()
K.noofsides()

Code 2
# Python program showing
www.profajaypashankar.com Page 24 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

# abstract class cannot


# be an 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()

b. Interfaces

Introduction to Interface in Python

An interface acts as a template for designing classes. Interfaces also define methods the same as
classes, but abstract methods, whereas class contains nonabstract methods. Abstract methods are
those methods without implementation or which are without the body. So the interface just defines the
abstract method without implementation. The implementation of these abstract methods is defined by
classes that implement an interface. In this topic, we are going to learn about Interface in Python.

Python interface design is different from other programming languages like C++, Java, C# and Go;
one difference is that all these languages use the keyword “interface”, whereas Python does not use it.
Another difference is Python does not require that a class which is implements an interface to provide
the definition for all the abstract methods of an interface.

How to Create Interface in Python?

There are two ways in python to create and implement the interface, which are –

 Informal Interfaces

 Formal Interfaces

1. Informal Interfaces

python informal interface is also a class that defines methods that can be overridden but without force
enforcement. An informal interface also called Protocols or Duck Typing. The duck typing is actually we
execute a method on the object as we expected an object to have, instead of checking the type of an
object. If its beaver is the same as we expected, then we will be fine and go farther, else if it does not,
things might get wrong, and for safety, we use a try..except block or hasattr to handle the exceptions
to check the object have the particular method or not.

www.profajaypashankar.com Page 25 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

An informal interface in python is termed as a protocol because it is informal and cannot be formally
enforced. It is mostly defined by templates or demonstrates in the documentations. Consider some of
the methods we usually used – __len__, __iter__, __contains__ and all, which are used to perform
some operation or set of protocols.

Example

Let see an example of python code to implements the – __len__, __iter__, __contains__ methods to
apply on user define class instance or object, as in the below-given code –

Code:

class Fruits :

def __init__( self, ele) :

self.__ele = ele

def __contains__( self, ele) :

return ele in self.__ele

def __len__( self ):

return len( self.__ele)

Fruits_list = Fruits([ "Apple", "Banana", "Orange" ])

print(len(Fruits_list))

print("Apple" in Fruits_list)

print("Mango" in Fruits_list)

print("Orange" not in Fruits_list)

Output:

As in the above example code, class Fruits implement the __len__, and __contains__ methods, so on
the instance of the Fruits class, we can directly use the len function to get the size and can check the
membership by using the in operator. As in the above code, the __iter__ method (iterable protocol) is
not implemented, so we would not iterate over the instance of the Fruits. Therefore an informal
interface cannot be enforced formally.

2. Formal Interfaces

A formal Interface is an interface which enforced formally. In some situations, the protocols or duck
typing creates confusion, like consider the example we have two classes FourWheelVehicle and
TwoWheelVehicle both have a method SpeedUp( ), so the object of both class can speedup, but both
objects are not the same even if both classes implement the same interface. So to resolve this
confusion, we can use the formal interface. To create a formal interface, we need to use ABCs
(Abstract Base Classes).

www.profajaypashankar.com Page 26 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

An ABC is simple as an interface or base classes define as an abstract class in nature and the abstract
class contains some methods as abstract. Next, if any classes or objects implement or drive from these
base classes, then these bases classes forced to implements all those methods. Note that the interface
cannot be instantiated, which means that we cannot create the object of the interface. So we use a
base class to create an object, and we can say that the object implements an interface. And we will
use the type function to confirm that the object implements a particular interface or not.

Example

Let see an example of python code to understand the formal interface with the general example where
we are trying to create an object of the abstract class, as in the below-given code –

Code:

import abc

class Myinterface( abc.ABC ) :

@abc.abstractclassmethod

def disp():

pass

class Myclass( Myinterface ) :

pass

o1 = Myclass( )

Output:

In the above code, the Myclass class inherits abstract class Myinterface but not provided the disp()
abstract method’s implementation. The class Myclass also becomes an abstract class and hence cannot
be instantiated.

Examples of Interface in Python

Here are the following examples mention below

Example #1

An example of python code for a derived class defines an abstract method.

Code:

import abc

class Myinterface( abc.ABC ):

@abc.abstractclassmethod

def disp( ):

pass

#print(" Hello from Myclass ")

class Myclass(Myinterface):

www.profajaypashankar.com Page 27 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

def disp( ):

pass

o1=Myclass()

Example #2

Example of python code for the derived class which defines an abstract method with the proper
definition –

Code:

import abc

class Myinterface( abc.ABC ):

@abc.abstractclassmethod

def disp( ):

pass

#print(" Hello from Myclass ")

class Myclass(Myinterface):

def disp(s):

print(" Hello from Myclass ")

o1=Myclass()

o1.disp()

Output:

Example #3

Example of python code to understand object types –

Code:

import abc

class FourWheelVehicle (abc.ABC):

@abc.abstractmethod

def SpeedUp( self ):

pass

class Car(FourWheelVehicle) :

def SpeedUp(self):

print(" Running! ")

s = Car()

print( isinstance(s, FourWheelVehicle))


www.profajaypashankar.com Page 28 of 29
FYCS SEM II ADVANCED PYTHON PROGRAMMING PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR

Output:

Example #4

Example of python code abstract class implemented by multiple derive classes –

Code:

import abc

class FourWheelVehicle (abc.ABC):

@abc.abstractmethod

def SpeedUp( self ):

pass

class Car(FourWheelVehicle) :

def SpeedUp(self):

print(" Running! ")

class TwoWheelVehicle (abc.ABC) :

@abc.abstractmethod

def SpeedUp(self):

pass

class Bike(TwoWheelVehicle) :

def SpeedUp(self) :

print(" Running!.. ")

a = Bike ()

s = Car()

print( isinstance(s, FourWheelVehicle))

print( isinstance(s, TwoWheelVehicle))

print( isinstance(a, FourWheelVehicle))

print( isinstance(a, TwoWheelVehicle))

Output:

www.profajaypashankar.com Page 29 of 29

You might also like