0% found this document useful (0 votes)
8 views105 pages

2advanced Python

In Python, a class serves as a blueprint for creating objects, encapsulating properties (attributes) and actions (methods). Classes can be defined using the 'class' keyword, and they can contain instance variables, static variables, and methods. The document also explains the concept of constructors, the types of variables, and how to access and delete instance variables.

Uploaded by

sharath.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views105 pages

2advanced Python

In Python, a class serves as a blueprint for creating objects, encapsulating properties (attributes) and actions (methods). Classes can be defined using the 'class' keyword, and they can contain instance variables, static variables, and methods. The document also explains the concept of constructors, the types of variables, and how to access and delete instance variables.

Uploaded by

sharath.s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 105

What is Class:

⚽ In Python every thing is an object. To create objects we required some Model or Plan
or Blue print, which is nothing but class.
⚽ We can write a class to represent properties (attributes) and actions (behaviour) of
object.

⚽ Properties can be represented by variables


⚽ Actions can be represented by Methods.

⚽ Hence class contains both variables and methods.

OOP’s
How to define a Class?
We can define a class by using class keyword.

Syntax:
class className:
''' documenttation string '''
variables:instance variables,static and local variables
methods: instance methods,static methods,class methods

Part - 1
Documentation string represents description of the class. Within the class doc string is
always optional. We can get doc string by using the following 2 ways.

1) print(classname.__doc__)
2) help(classname)

Example:

1) class Student:
2) ''''' This is student class with required data'''
3) print(Student.__doc__)
4) help(Student)

Within the Python class we can represent data by using variables.

There are 3 types of variables are allowed.

1) Instance Variables (Object Level Variables)


2) Static Variables (Class Level Variables)
3) Local variables (Method Level Variables)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
1  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
2  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Within the Python class, we can represent operations by using methods. The following are 8) def talk(self):
various types of allowed methods 9) print("Hello My Name is:",self.name)
10) print("My Rollno is:",self.rollno)
1) Instance Methods 11) print("My Marks are:",self.marks)
2) Class Methods 12)
3) Static Methods 13) s1=Student("Durga",101,80)
14) s1.talk()
Example for Class:
Output:
1) class Student: D:\durgaclasses>py test.py
2) '''''Developed by durga for python demo''' Hello My Name is: Durga
3) def __init__(self): My Rollno is: 101
4) self.name='durga' My Marks are: 80
5) self.age=40
6) self.marks=80
7)
Self Variable:
8) def talk(self):  self is the default variable which is always pointing to current object (like this keyword
9) print("Hello I am :",self.name) in Java)
10) print("My Age is:",self.age)  By using self we can access instance variables and instance methods of object.
11) print("My Marks are:",self.marks)
Note:
1) self should be first parameter inside constructor
What is Object: def __init__(self):
Pysical existence of a class is nothing but object. We can create any number of objects for 2) self should be first parameter inside instance methods
a class. def talk(self):

Syntax to Create Object: referencevariable = classname()


Constructor Concept:
Example: s = Student() ☕ Constructor is a special method in python.
☕ The name of the constructor should be __init__(self)
☕ Constructor will be executed automatically at the time of object creation.
What is Reference Variable? ☕ The main purpose of constructor is to declare and initialize instance variables.
The variable which can be used to refer object is called reference variable. ☕ Per object constructor will be exeucted only once.
By using reference variable, we can access properties and methods of object.
☕ Constructor can take atleast one argument(atleast self)
☕ Constructor is optional and if we are not providing any constructor then python will
Program: Write a Python program to create a Student class and Creates an object to it. provide default constructor.
Call the method talk() to display student details
Example:
1) class Student:
2) 1) def __init__(self,name,rollno,marks):
3) def __init__(self,name,rollno,marks): 2) self.name=name
4) self.name=name 3) self.rollno=rollno
5) self.rollno=rollno 4) self.marks=marks
6) self.marks=marks
7)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
3  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
4  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Program to demonistrate Constructor will execute only once per Object: Student Name:Sunny
Rollno:102
1) class Test: Marks:100
2)
3) def __init__(self):
4) print("Constructor exeuction...") Differences between Methods and Constructors
5) Method Constructor
6) def m1(self): 1) Name of method can be any name 1) Constructor name should be always __init__
7) print("Method execution...") 2) Method will be executed if we call that 2) Constructor will be executed automatically at
8) method the time of object creation.
9) t1=Test() 3) Per object, method can be called any number 3) Per object, Constructor will be executed only
10) t2=Test() of times. once
11) t3=Test() 4) Inside method we can write business logic 4) Inside Constructor we have to declare and
12) t1.m1() initialize instance variables

Output
Constructor exeuction... Types of Variables:
Constructor exeuction...
Constructor exeuction... Inside Python class 3 types of variables are allowed.
Method execution...
1) Instance Variables (Object Level Variables)
Program: 2) Static Variables (Class Level Variables)
3) Local variables (Method Level Variables)
1) class Student:
2)
3) ''''' This is student class with required data''' 1) Instance Variables:
4) def __init__(self,x,y,z):  If the value of a variable is varied from object to object, then such type of variables are
5) self.name=x called instance variables.
6) self.rollno=y  For every object a separate copy of instance variables will be created.
7) self.marks=z
8) Where we can declare Instance Variables:
9) def display(self): 1) Inside Constructor by using self variable
10) print("Student Name:{}\nRollno:{} \nMarks:{}".format(self.name,self.rollno,self 2) Inside Instance Method by using self variable
.marks)) 3) Outside of the class by using object reference variable
11)
12) s1=Student("Durga",101,80)
13) s1.display() 1) Inside Constructor by using Self Variable:
14) s2=Student("Sunny",102,100) We can declare instance variables inside a constructor by using self keyword. Once we
15) s2.display() creates object, automatically these variables will be added to the object.

Output 1) class Employee:


Student Name:Durga 2)
Rollno:101 3) def __init__(self):
Marks:80 4) self.eno=100
5) self.ename='Durga'

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
5  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
6  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
6) self.esal=10000 How to Access Instance Variables:
7)
We can access instance variables with in the class by using self variable and outside of the
8) e=Employee()
class by using object reference.
9) print(e.__dict__)
1) class Test:
Output: {'eno': 100, 'ename': 'Durga', 'esal': 10000}
2)
3) def __init__(self):
2) Inside Instance Method by using Self Variable: 4) self.a=10
We can also declare instance variables inside instance method by using self variable. If 5) self.b=20
any instance variable declared inside instance method, that instance variable will be 6) def display(self):
added once we call taht method. 7) print(self.a)
8) print(self.b)
1) class Test: 9)
2) 10) t=Test()
3) def __init__(self): 11) t.display()
4) self.a=10 12) print(t.a,t.b)
5) self.b=20
6) Output
7) def m1(self): 10
8) self.c=30 20
9) 10 20
10) t=Test()
11) t.m1() How to delete Instance Variable from the Object:
12) print(t.__dict__)
1) Within a class we can delete instance variable as follows
del self.variableName
Output: {'a': 10, 'b': 20, 'c': 30}
2) From outside of class we can delete instance variables as follows
3) Outside of the Class by using Object Reference Variable: del objectreference.variableName
We can also add instance variables outside of a class to a particular object.
1) class Test:
1) class Test: 2) def __init__(self):
2) 3) self.a=10
3) def __init__(self): 4) self.b=20
4) self.a=10 5) self.c=30
5) self.b=20 6) self.d=40
6) def m1(self): 7) def m1(self):
7) self.c=30 8) del self.d
8) 9)
9) t=Test() 10) t=Test()
10) t.m1() 11) print(t.__dict__)
11) t.d=40 12) t.m1()
12) print(t.__dict__) 13) print(t.__dict__)
14) del t.c
Output {'a': 10, 'b': 20, 'c': 30, 'd': 40} 15) print(t.__dict__)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
7  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
8  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output 2) Static Variables:
{'a': 10, 'b': 20, 'c': 30, 'd': 40}
{'a': 10, 'b': 20, 'c': 30} ☕ If the value of a variable is not varied from object to object, such type of variables we
{'a': 10, 'b': 20} have to declare with in the class directly but outside of methods. Such types of
variables are called Static variables.
Note: The instance variables which are deleted from one object,will not be deleted from ☕ For total class only one copy of static variable will be created and shared by all objects
other objects. of that class.
☕ We can access static variables either by class name or by object reference. But
1) class Test: recommended to use class name.
2) def __init__(self):
3) self.a=10 Instance Variable vs Static Variable:
4) self.b=20
5) self.c=30 Note: In the case of instance variables for every object a seperate copy will be
6) self.d=40
created,but in the case of static variables for total class only one copy will be created and
7)
shared by every object of that class.
8) t1=Test()
9) t2=Test() 1) class Test:
10) del t1.a 2) x=10
11) print(t1.__dict__) 3) def __init__(self):
12) print(t2.__dict__) 4) self.y=20
5)
Output
6) t1=Test()
{'b': 20, 'c': 30, 'd': 40}
7) t2=Test()
{'a': 10, 'b': 20, 'c': 30, 'd': 40}
8) print('t1:',t1.x,t1.y)
9) print('t2:',t2.x,t2.y)
If we change the values of instance variables of one object then those changes won't be
10) Test.x=888
reflected to the remaining objects, because for every object we are separate copy of
11) t1.y=999
instance variables are available.
12) print('t1:',t1.x,t1.y)
13) print('t2:',t2.x,t2.y)
1) class Test:
2) def __init__(self):
3) self.a=10
Output
4) self.b=20 t1: 10 20
5) t2: 10 20
6) t1=Test() t1: 888 999
7) t1.a=888 t2: 888 20
8) t1.b=999
9) t2=Test()
10) print('t1:',t1.a,t1.b) Various Places to declare Static Variables:
11) print('t2:',t2.a,t2.b) 1) In general we can declare within the class directly but from out side of any method
2) Inside constructor by using class name
Output 3) Inside instance method by using class name
t1: 888 999 4) Inside classmethod by using either class name or cls variable
t2: 10 20 5) Inside static method by using class name

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
9  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
10  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) class Test: 13) @staticmethod
2) a=10 14) def m3():
3) def __init__(self): 15) print(Test.a)
4) Test.b=20 16) t=Test()
5) def m1(self): 17) print(Test.a)
6) Test.c=30 18) print(t.a)
7) @classmethod 19) t.m1()
8) def m2(cls): 20) t.m2()
9) cls.d1=40 21) t.m3()
10) Test.d2=400
11) @staticmethod Where we can modify the Value of Static Variable:
12) def m3():
Anywhere either with in the class or outside of class we can modify by using classname.
13) Test.e=50
But inside class method, by using cls variable.
14) print(Test.__dict__)
15) t=Test()
1) class Test:
16) print(Test.__dict__)
2) a=777
17) t.m1()
3) @classmethod
18) print(Test.__dict__) 4) def m1(cls):
19) Test.m2() 5) cls.a=888
20) print(Test.__dict__) 6) @staticmethod
21) Test.m3() 7) def m2():
22) print(Test.__dict__) 8) Test.a=999
23) Test.f=60 9) print(Test.a)
24) print(Test.__dict__)
10) Test.m1()
11) print(Test.a)
How to access Static Variables: 12) Test.m2()
1) inside constructor: by using either self or classname 13) print(Test.a)
2) inside instance method: by using either self or classname
3) inside class method: by using either cls variable or classname Output
4) inside static method: by using classname 777
5) From outside of class: by using either object reference or classname 888
999
1) class Test:
2) a=10 *****
3) def __init__(self): If we change the Value of Static Variable by using either self OR
4) print(self.a) Object Reference Variable:
5) print(Test.a) If we change the value of static variable by using either self or object reference variable,
6) def m1(self): then the value of static variable won't be changed, just a new instance variable with that
7) print(self.a) name will be added to that particular object.
8) print(Test.a)
9) @classmethod 1) class Test:
10) def m2(cls): 2) a=10
11) print(cls.a) 3) def m1(self):
12) print(Test.a) 4) self.a=888

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
11  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
12  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) t1=Test() 1) class Test:
6) t1.m1() 2) a=10
7) print(Test.a) 3) def __init__(self):
8) print(t1.a) 4) self.b=20
5) def m1(self):
Output 6) self.a=888
10 7) self.b=999
888 8)
9) t1=Test()
1) class Test: 10) t2=Test()
2) x=10 11) t1.m1()
3) def __init__(self): 12) print(t1.a,t1.b)
4) self.y=20 13) print(t2.a,t2.b)
5)
6) t1=Test() Output
7) t2=Test() 888 999
8) print('t1:',t1.x,t1.y) 10 20
9) print('t2:',t2.x,t2.y)
10) t1.x=888 1) class Test:
11) t1.y=999 2) a=10
12) print('t1:',t1.x,t1.y) 3) def __init__(self):
13) print('t2:',t2.x,t2.y) 4) self.b=20
5) @classmethod
Output 6) def m1(cls):
t1: 10 20 7) cls.a=888
t2: 10 20 8) cls.b=999
t1: 888 999 9)
t2: 10 20 10) t1=Test()
11) t2=Test()
1) class Test: 12) t1.m1()
2) a=10 13) print(t1.a,t1.b)
3) def __init__(self): 14) print(t2.a,t2.b)
4) self.b=20 15) print(Test.a,Test.b)
5) t1=Test()
6) t2=Test() Output
7) Test.a=888 888 20
8) t1.b=999 888 20
9) print(t1.a,t1.b) 888 999
10) print(t2.a,t2.b)

Output
888 999
888 20

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
13  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
14  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
28) del Test.e
How to Delete Static Variables of a Class: 29) print(Test.__dict__)
1) We can delete static variables from anywhere by using the following syntax
del classname.variablename
****Note:
⚽ By using object reference variable/self we can read static variables, but we cannot
2) But inside classmethod we can also use cls variable
modify or delete.
del cls.variablename
⚽ If we are trying to modify, then a new instance variable will be added to that
1) class Test: particular object.
2) a=10 ⚽ t1.a = 70
3) @classmethod ⚽ If we are trying to delete then we will get error.
4) def m1(cls):
5) del cls.a Example:
6) Test.m1()
7) print(Test.__dict__) 1) class Test:
2) a=10
Example: 3)
4) t1=Test()
1) class Test: 5) del t1.a ===>AttributeError: a
2) a=10
3) def __init__(self): We can modify or delete static variables only by using classname or cls variable.
4) Test.b=20
5) del Test.a 1) import sys
6) def m1(self): 2) class Customer:
7) Test.c=30 3) ''''' Customer class with bank operations.. '''
8) del Test.b 4) bankname='DURGABANK'
9) @classmethod 5) def __init__(self,name,balance=0.0):
10) def m2(cls): 6) self.name=name
11) cls.d=40 7) self.balance=balance
12) del Test.c 8) def deposit(self,amt):
13) @staticmethod 9) self.balance=self.balance+amt
14) def m3(): 10) print('Balance after deposit:',self.balance)
15) Test.e=50 11) def withdraw(self,amt):
16) del Test.d 12) if amt>self.balance:
17) print(Test.__dict__) 13) print('Insufficient Funds..cannot perform this operation')
18) t=Test() 14) sys.exit()
19) print(Test.__dict__) 15) self.balance=self.balance-amt
20) t.m1() 16) print('Balance after withdraw:',self.balance)
21) print(Test.__dict__) 17)
22) Test.m2() 18) print('Welcome to',Customer.bankname)
23) print(Test.__dict__) 19) name=input('Enter Your Name:')
24) Test.m3() 20) c=Customer(name)
25) print(Test.__dict__) 21) while True:
26) Test.f=60 22) print('d-Deposit \nw-Withdraw \ne-exit')
27) print(Test.__dict__) 23) option=input('Choose your option:')

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
15  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
16  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
24) if option=='d' or option=='D': e-exit
25) amt=float(input('Enter amount:'))
26) c.deposit(amt) Choose your option:e
27) elif option=='w' or option=='W': Thanks for Banking
28) amt=float(input('Enter amount:'))
29) c.withdraw(amt)
30) elif option=='e' or option=='E':
3) Local Variables:
31) print('Thanks for Banking') ⚽ Sometimes to meet temporary requirements of programmer,we can declare variables
32) sys.exit() inside a method directly,such type of variables are called local variable or temporary
33) else: variables.
34) print('Invalid option..Plz choose valid option') ⚽ Local variables will be created at the time of method execution and destroyed once
method completes.
Output: ⚽ Local variables of a method cannot be accessed from outside of method.
D:\durga_classes>py test.py
Welcome to DURGABANK 1) class Test:
Enter Your Name:Durga 2) def m1(self):
d-Deposit 3) a=1000
w-Withdraw 4) print(a)
e-exit 5) def m2(self):
6) b=2000
Choose your option:d 7) print(b)
Enter amount:10000 8) t=Test()
Balance after deposit: 10000.0 9) t.m1()
d-Deposit 10) t.m2()
w-Withdraw
e-exit Output
1000
Choose your option:d 2000
Enter amount:20000
Balance after deposit: 30000.0 1) class Test:
d-Deposit 2) def m1(self):
w-Withdraw 3) a=1000
e-exit 4) print(a)
5) def m2(self):
Choose your option:w 6) b=2000
Enter amount:2000 7) print(a) #NameError: name 'a' is not defined
Balance after withdraw: 28000.0 8) print(b)
d-Deposit 9) t=Test()
w-Withdraw 10) t.m1()
e-exit 11) t.m2()

Choose your option:r


Invalid option..Plz choose valid option
d-Deposit
w-Withdraw

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
17  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
18  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Enter Name:Durga
Types of Methods: Enter Marks:90
Inside Python class 3 types of methods are allowed Hi Durga
Your Marks are: 90
1) Instance Methods You got First Grade
2) Class Methods
3) Static Methods Enter Name:Ravi
Enter Marks:12
1) Instance Methods: Hi Ravi
⚽ Inside method implementation if we are using instance variables then such type of Your Marks are: 12
methods are called instance methods. You are Failed
⚽ Inside instance method declaration, we have to pass self variable. def m1(self):
⚽ By using self variable inside method we can able to access instance variables. Setter and Getter Methods:
⚽ Within the class we can call instance method by using self variable and from outside of We can set and get the values of instance variables by using getter and setter methods.
the class we can call by using object reference.

1) class Student:
Setter Method:
setter methods can be used to set values to the instance variables. setter methods also
2) def __init__(self,name,marks):
known as mutator methods.
3) self.name=name
4) self.marks=marks
Syntax:
5) def display(self):
def setVariable(self,variable):
6) print('Hi',self.name)
self.variable=variable
7) print('Your Marks are:',self.marks)
8) def grade(self): Example:
9) if self.marks>=60: def setName(self,name):
10) print('You got First Grade') self.name=name
11) elif self.marks>=50:
12) print('Yout got Second Grade')
13) elif self.marks>=35: Getter Method:
14) print('You got Third Grade') Getter methods can be used to get values of the instance variables. Getter methods also
15) else: known as accessor methods.
16) print('You are Failed')
17) n=int(input('Enter number of students:')) Syntax:
18) for i in range(n): def getVariable(self):
19) name=input('Enter Name:') return self.variable
20) marks=int(input('Enter Marks:'))
21) s= Student(name,marks) Example:
22) s.display() def getName(self):
23) s.grade() return self.name
24) print()
1) class Student:
Ouput: 2) def setName(self,name):
D:\durga_classes>py test.py 3) self.name=name
Enter number of students:2 4)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
19  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
20  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) def getName(self): 1) class Animal:
6) return self.name 2) lEgs=4
7) 3) @classmethod
8) def setMarks(self,marks): 4) def walk(cls,name):
9) self.marks=marks 5) print('{} walks with {} lEgs...'.format(name,cls.lEgs))
10) 6) Animal.walk('Dog')
11) def getMarks(self): 7) Animal.walk('Cat')
12) return self.marks
13) Output
14) n=int(input('Enter number of students:')) D:\python_classes>py test.py
15) for i in range(n): Dog walks with 4 lEgs...
16) s=Student() Cat walks with 4 lEgs...
17) name=input('Enter Name:')
18) s.setName(name) Program to track the Number of Objects created for a Class:
19) marks=int(input('Enter Marks:'))
20) s.setMarks(marks) 1) class Test:
21) 2) count=0
22) print('Hi',s.getName()) 3) def __init__(self):
23) print('Your Marks are:',s.getMarks()) 4) Test.count =Test.count+1
24) print() 5) @classmethod
6) def noOfObjects(cls):
Output: 7) print('The number of objects created for test class:',cls.count)
D:\python_classes>py test.py 8)
Enter number of students:2 9) t1=Test()
10) t2=Test()
Enter Name:Durga 11) Test.noOfObjects()
Enter Marks:100 12) t3=Test()
Hi Durga 13) t4=Test()
Your Marks are: 100 14) t5=Test()
15) Test.noOfObjects()
Enter Name:Ravi
Enter Marks:80
Hi Ravi 3) Static Methods:
Your Marks are: 80 ⚽ In general these methods are general utility methods.
⚽ Inside these methods we won't use any instance or class variables.
2) Class Methods: ⚽ Here we won't provide self or cls arguments at the time of declaration.
⚽ Inside method implementation if we are using only class variables (static variables), ⚽ We can declare static method explicitly by using @staticmethod decorator
then such type of methods we should declare as class method. ⚽ We can access static methods by using classname or object reference
⚽ We can declare class method explicitly by using @classmethod decorator.
1) class DurgaMath:
⚽ For class method we should provide cls variable at the time of declaration
2)
⚽ We can call classmethod by using classname or object reference variable.
3) @staticmethod
4) def add(x,y):
5) print('The Sum:',x+y)
6)
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
21  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
22  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
7) @staticmethod Output
8) def product(x,y): D:\python_classes>py test.py
9) print('The Product:',x*y) Employee Number: 100
10) Employee Name: Durga
11) @staticmethod Employee Salary: 20000
12) def average(x,y):
13) print('The average:',(x+y)/2) In the above application, Employee class members are available to Test class.

Inner Classes
14)
15) DurgaMath.add(10,20)
16) DurgaMath.product(10,20)
17) DurgaMath.average(10,20)

Output Sometimes we can declare a class inside another class, such type of classes are called
The Sum: 30 inner classes.
The Product: 200
The average: 15.0 Without existing one type of object if there is no chance of existing another type of object,
then we should go for inner classes.
Note:
 In general we can use only instance and static methods.Inside static method we can Example: Without existing Car object there is no chance of existing Engine object. Hence
access class level variables by using class name. Engine class should be part of Car class.
 Class methods are most rarely used methods in python.
class Car:
.....
Passing Members of One Class to Another Class: class Engine:
We can access members of one class inside another class.
......
1) class Employee:
2) def __init__(self,eno,ename,esal): Example: Without existing university object there is no chance of existing Department
3) self.eno=eno object
4) self.ename=ename
5) self.esal=esal class University:
6) def display(self): .....
7) print('Employee Number:',self.eno) class Department:
8) print('Employee Name:',self.ename) ......
9) print('Employee Salary:',self.esal)
10) class Test: Example: Without existing Human there is no chance of existin Head. Hence Head
11) def modify(emp): should be part of Human.
12) emp.esal=emp.esal+10000
13) emp.display() class Human:
14) e=Employee(100,'Durga',10000) class Head:
15) Test.modify(e)
Note: Without existing outer class object there is no chance of existing inner class object.
Hence inner class object is always associated with outer class object.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
23  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
24  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Demo Program-1: 14) p=Person()
15) p.display()
1) class Outer: 16) x=p.db
2) def __init__(self): 17) x.display()
3) print("outer class object creation")
4) class Inner: Output
5) def __init__(self): Name: durga
6) print("inner class object creation") Dob=10/5/1947
7) def m1(self):
8) print("inner class method") Demo Program-3:
9) o=Outer() Inside a class we can declare any number of inner classes.
10) i=o.Inner()
11) i.m1() 1) class Human:
2)
Output 3) def __init__(self):
outer class object creation 4) self.name = 'Sunny'
inner class object creation 5) self.head = self.Head()
inner class method 6) self.brain = self.Brain()
7) def display(self):
Note: The following are various possible syntaxes for calling inner class method 8) print("Hello..",self.name)
9)
1) o = Outer() 10) class Head:
i = o.Inner() 11) def talk(self):
i.m1() 12) print('Talking...')
13)
2) i = Outer().Inner() 14) class Brain:
i.m1() 15) def think(self):
16) print('Thinking...')
3) Outer().Inner().m1() 17)
18) h=Human()
Demo Program-2: 19) h.display()
20) h.head.talk()
1) class Person: 21) h.brain.think()
2) def __init__(self):
3) self.name='durga' Output
4) self.db=self.Dob() Hello.. Sunny
5) def display(self): Talking...
6) print('Name:',self.name) Thinking...
7) class Dob:
8) def __init__(self):
9) self.dd=10
10) self.mm=5
11) self.yy=1947
12) def display(self):
13) print('Dob={}/{}/{}'.format(self.dd,self.mm,self.yy))
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
25  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
26  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Garbage Collection Destructors:
⚽ Destructor is a special method and the name should be __del__
⚽ Just before destroying an object Garbage Collector always calls destructor to perform
⚽ In old languages like C++, programmer is responsible for both creation and destruction clean up activities (Resource deallocation activities like close database connection etc).
of objects.Usually programmer taking very much care while creating object, but ⚽ Once destructor execution completed then Garbage Collector automatically destroys
nEglecting destruction of useless objects. Because of his nEglectance, total memory that object.
can be filled with useless objects which creates memory problems and total
application will be down with Out of memory error. Note: The job of destructor is not to destroy object and it is just to perform clean up
activities.
⚽ But in Python, We have some assistant which is always running in the background to
destroy useless objects.Because this assistant the chance of failing Python program 1) import time
with memory problems is very less. This assistant is nothing but Garbage Collector. 2) class Test:
⚽ Hence the main objective of Garbage Collector is to destroy useless objects. 3) def __init__(self):
4) print("Object Initialization...")
⚽ If an object does not have any reference variable then that object eligible for Garbage 5) def __del__(self):
Collection. 6) print("Fulfilling Last Wish and performing clean up activities...")
7)
8) t1=Test()
How to enable and disable Garbage Collector in our 9) t1=None
Program: 10) time.sleep(5)
By default Gargbage collector is enabled, but we can disable based on our requirement. In 11) print("End of application")
this context we can use the following functions of gc module.
Output
1) gc.isenabled()  Returns True if GC enabled Object Initialization...
Fulfilling Last Wish and performing clean up activities...
2) gc.disable() To disable GC explicitly End of application

3) gc.enable() To enable GC explicitly Note: If the object does not contain any reference variable then only it is eligible fo GC. ie
if the reference count is zero then only object eligible for GC.
1) import gc
2) print(gc.isenabled()) 1) import time
3) gc.disable() 2) class Test:
4) print(gc.isenabled()) 3) def __init__(self):
5) gc.enable() 4) print("Constructor Execution...")
6) print(gc.isenabled()) 5) def __del__(self):
6) print("Destructor Execution...")
7)
Output
8) t1=Test()
True
9) t2=t1
False
10) t3=t2
True
11) del t1
12) time.sleep(5)
13) print("object not yet destroyed after deleting t1")
14) del t2

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
27  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
28  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
15) time.sleep(5)
16) print("object not yet destroyed even after deleting t2")
17) print("I am trying to delete last reference variable...")
18) del t3

Example:

1) import time
2) class Test:
3) def __init__(self):
4) print("Constructor Execution...")
5) def __del__(self):
6) print("Destructor Execution...")
7)

OOP’s
8) list=[Test(),Test(),Test()]
9) del list
10) time.sleep(5)
11) print("End of application")

Output
Constructor Execution...
Constructor Execution...
Constructor Execution...
Destructor Execution...
Destructor Execution...

Part - 2
Destructor Execution...
End of application

How to find the Number of References of an Object:


sys module contains getrefcount() function for this purpose.
sys.getrefcount (objectreference)

1) import sys
2) class Test:
3) pass
4) t1=Test()
5) t2=t1
6) t3=t1
7) t4=t1
8) print(sys.getrefcount(t1))

Output 5

Note: For every object, Python internally maintains one default reference variable self.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
29  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
30  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
6) print('Engine Specific Functionality')
Agenda 7) class Car:
8) def __init__(self):
9) self.engine=Engine()
 Inheritance 10) def m2(self):
 Has-A Relationship 11) print('Car using Engine Class Functionality')
 IS-A Relationship 12) print(self.engine.a)
13) print(self.engine.b)
 IS-A vs HAS-A Relationship 14) self.engine.m1()
 Composition vs Aggregation 15) c=Car()
16) c.m2()

 Types of Inheritance Output:


 Single Inheritance Car using Engine Class Functionality
 Multi Level Inheritance 10
 Hierarchical Inheritance 20
 Multiple Inheritance Engine Specific Functionality
 Hybrid Inheritance Demo Program-2:
 Cyclic Inheritance
1) class Car:
 Method Resolution Order (MRO) 2) def __init__(self,name,model,color):
3) self.name=name
 super() Method 4) self.model=model
5) self.color=color
6) def getinfo(self):
Using Members of One Class inside Another Class: 7) print("Car Name:{} , Model:{} and Color:{}".format(self.name,self.model,self.c
We can use members of one class inside another class by using the following ways olor))
8)
1) By Composition (Has-A Relationship) 9) class Employee:
2) By Inheritance (IS-A Relationship) 10) def __init__(self,ename,eno,car):
11) self.ename=ename
12) self.eno=eno
1) By Composition (Has-A Relationship): 13) self.car=car
 By using Class Name or by creating object we can access members of one class inside 14) def empinfo(self):
another class is nothing but composition (Has-A Relationship). 15) print("Employee Name:",self.ename)
 The main advantage of Has-A Relationship is Code Reusability. 16) print("Employee Number:",self.eno)
17) print("Employee Car Info:")
Demo Program-1: 18) self.car.getinfo()
19) c=Car("Innova","2.5V","Grey")
1) class Engine: 20) e=Employee('Durga',10000,c)
2) a=10 21) e.empinfo()
3) def __init__(self):
4) self.b=20
5) def m1(self):

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
31  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
32  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output: 2) By Inheritance (IS-A Relationship):
Employee Name: Durga What ever variables, methods and constructors available in the parent class by default
Employee Number: 10000 available to the child classes and we are not required to rewrite. Hence the main
Employee Car Info: advantage of inheritance is Code Reusability and we can extend existing functionality
Car Name: Innova, Model: 2.5V and Color:Grey with some more extra functionality.
In the above program Employee class Has-A Car reference and hence Employee class can
Syntax: class childclass(parentclass)
access all members of Car class.
1) class P:
Demo Program-3: 2) a=10
3) def __init__(self):
1) class X:
4) self.b=10
2) a=10
5) def m1(self):
3) def __init__(self):
6) print('Parent instance method')
4) self.b=20
7) @classmethod
5) def m1(self):
8) def m2(cls):
6) print("m1 method of X class")
9) print('Parent class method')
7)
10) @staticmethod
8) class Y:
11) def m3():
9) c=30 12) print('Parent static method')
10) def __init__(self):
13)
11) self.d=40
14) class C(P):
12) def m2(self):
15) pass
13) print("m2 method of Y class")
16)
14)
17) c=C()
15) def m3(self):
18) print(c.a)
16) x1=X()
19) print(c.b)
17) print(x1.a)
20) c.m1()
18) print(x1.b)
21) c.m2()
19) x1.m1() 22) c.m3()
20) print(Y.c)
21) print(self.d)
Output:
22) self.m2()
10
23) print("m3 method of Y class")
10
24) y1=Y()
Parent instance method
25) y1.m3()
Parent class method
Parent static method
Output:
10 1) class P:
20 2) 10 methods
m1 method of X class 3) class C(P):
30 4) 5 methods
40
m2 method of Y class
m3 method of Y class

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
33  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
34  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
In the above example Parent class contains 10 methods and these methods automatically Demo program for Inheritance:
available to the child class and we are not required to rewrite those methods(Code
Reusability) 1) class Person:
Hence child class contains 15 methods. 2) def __init__(self,name,age):
3) self.name=name
Note: What ever members present in Parent class are by default available to the child 4) self.age=age
class through inheritance. 5) def eatndrink(self):
6) print('Eat Biryani and Drink Beer')
1) class P: 7)
2) def m1(self): 8) class Employee(Person):
3) print("Parent class method") 9) def __init__(self,name,age,eno,esal):
4) class C(P): 10) super().__init__(name,age)
5) def m2(self): 11) self.eno=eno
6) print("Child class method") 12) self.esal=esal
7) 13)
8) c=C(); 14) def work(self):
9) c.m1() 15) print("Coding Python is very easy just like drinking Chilled Beer")
10) c.m2() 16) def empinfo(self):
17) print("Employee Name:",self.name)
Output: 18) print("Employee Age:",self.age)
Parent class method 19) print("Employee Number:",self.eno)
Child class method 20) print("Employee Salary:",self.esal)
21)
What ever methods present in Parent class are automatically available to the child class 22) e=Employee('Durga', 48, 100, 10000)
and hence on the child class reference we can call both parent class methods and child 23) e.eatndrink()
class methods. 24) e.work()
25) e.empinfo()
Similarly variables also
Output:
1) class P: Eat Biryani and Drink Beer
2) a=10 Coding Python is very easy just like drinking Chilled Beer
3) def __init__(self): Employee Name: Durga
4) self.b=20 Employee Age: 48
5) class C(P): Employee Number: 100
6) c=30 Employee Salary: 10000
7) def __init__(self):
8) super().__init__()===>Line-1
9)
10)
self.d=30
IS-A vs HAS-A Relationship:
11) c1=C()  If we want to extend existing functionality with some more extra functionality then we
12) print(c1.a,c1.b,c1.c,c1.d) should go for IS-A Relationship.
 If we dont want to extend and just we have to use existing functionality then we
If we comment Line-1 then variable b is not available to the child class. should go for HAS-A Relationship.
 Eg: Employee class extends Person class Functionality But Employee class just uses Car
functionality but not extending

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
35  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
36  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
35) e.work()
Person 36) e.empinfo()

Output:
IS - A Eat Biryani and Drink Beer
Coding Python is very easy just like drinking Chilled Beer
Employee Name: Durga
HAS - A Employee Age: 48
Employee Car
Employee Number: 100
Employee Salary: 10000
1) class Car: Employee Car Info:
2) def __init__(self,name,model,color): Car Name:Innova
3) self.name=name Model:2.5V
4) self.model=model Color:Grey
5) self.color=color
6) def getinfo(self): In the above example Employee class extends Person class functionality but just uses Car
7) print("\tCar Name:{} \n\t Model:{} \n\t Color:{}".format(self.name,self.model, class functionality.
self.color))
8)
9) class Person:
10) def __init__(self,name,age):
Composition vs Aggregation:
11) self.name=name
12) self.age=age
13) def eatndrink(self): Composition:
14) print('Eat Biryani and Drink Beer') Without existing container object if there is no chance of existing contained object then
15) the container and contained objects are strongly associated and that strong association is
16) class Employee(Person): nothing but Composition.
17) def __init__(self,name,age,eno,esal,car):
18) super().__init__(name,age) Eg: University contains several Departments and without existing university object there
19) self.eno=eno is no chance of existing Department object. Hence University and Department objects are
20) self.esal=esal strongly associated and this strong association is nothing but Composition.
21) self.car=car
22) def work(self):
23) print("Coding Python is very easy just like drinking Chilled Beer")
24) def empinfo(self): Department Object
25) print("Employee Name:",self.name) (Contained Object)
26) print("Employee Age:",self.age)
27) print("Employee Number:",self.eno)
28) print("Employee Salary:",self.esal)
29) print("Employee Car Info:")
30) self.car.getinfo()
31)
32) c=Car("Innova","2.5V","Grey") University Object
33) e=Employee('Durga',48,100,10000,c) (Container Object)
34) e.eatndrink()

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
37  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
38  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Aggregation: Conclusion:
Without existing container object if there is a chance of existing contained object then the The relation between object and its instance variables is always Composition where as the
container and contained objects are weakly associated and that weak association is relation between object and static variables is Aggregation.
nothing but Aggregation.
Note: Whenever we are creating child class object then child class constructor will be
Eg: Department contains several Professors. Without existing Department still there may executed. If the child class does not contain constructor then parent class constructor will
be a chance of existing Professor. Hence Department and Professor Objects are weakly be executed, but parent object won't be created.
associated, which is nothing but Aggregation.
1) class P:
2) def __init__(self):
3) print(id(self))
4) class C(P):

(Contained Object)
Professor Object
5) pass
x 6) c=C()
x 7) print(id(c))
: :
: : Output:
6207088
: :
6207088
x
1) class Person:
Department Object 2) def __init__(self,name,age):
(Container Object) 3) self.name=name
4) self.age=age
5) class Student(Person):
Coding Example:
6) def __init__(self,name,age,rollno,marks):
7) super().__init__(name,age)
1) class Student:
8) self.rollno=rollno
2) collegeName='DURGASOFT'
9) self.marks=marks
3) def __init__(self,name):
10) def __str__(self):
4) self.name=name
11) return 'Name={}\nAge={}\nRollno={}\nMarks={}'.format(self.name,self.age,sel
5) print(Student.collegeName)
f.rollno,self.marks)
6) s=Student('Durga')
7) print(s.name)
12) s1=Student('durga',48,101,90)
13) print(s1)

Output:
DURGASOFT
Output:
Durga Name=durga
Age=48
In the above example without existing Student object there is no chance of existing his Rollno=101
name. Hence Student Object and his name are strongly associated which is nothing but Marks=90
Composition.
Note: In the above example when ever we are creating child class object both parent and
But without existing Student object there may be a chance of existing collegeName. Hence child class constructors got executed to perform initialization of child object.
Student object and collegeName are weakly associated which is nothing but Aggregation.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
39  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
40  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
11) c.m1()
Types of Inheritance: 12) c.m2()
13) c.m3()
1) Single Inheritance:
The concept of inheriting the properties from one class to another class is known as Output:
single inheritance. Parent Method
Child Method
1) class P: Sub Child Method
2) def m1(self):
3) print("Parent Method") P
4) class C(P):
5) def m2(self):
6) print("Child Method")
7) c=C()
8) c.m1()
9) c.m2() C Multi – Level Inheritance

Output:
Parent Method
Child Method

CC
P

Single Inheritance 3) Hierarchical Inheritance:


The concept of inheriting properties from one class into multiple classes which are
present at same level is known as Hierarchical Inheritance
C

P
2) Multi Level Inheritance:
The concept of inheriting the properties from multiple classes to single class with the
concept of one after another is known as multilevel inheritance.

1) class P: C1 C2
2) def m1(self):
3) print("Parent Method") Hierarchical
4) class C(P):
5) def m2(self): Inheritance
6) print("Child Method")
7) class CC(C): 1) class P:
8) def m3(self): 2) def m1(self):
9) print("Sub Child Method") 3) print("Parent Method")
10) c=CC() 4) class C1(P):

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
41  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
42  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) def m2(self): 10) c=C()
6) print("Child1 Method") 11) c.m1()
7) class C2(P): 12) c.m2()
8) def m3(self): 13) c.m3()
9) print("Child2 Method")
10) c1=C1() Output:
11) c1.m1() Parent1 Method
12) c1.m2() Parent2 Method
13) c2=C2() Child2 Method
14) c2.m1()
15) c2.m3() If the same method is inherited from both parent classes, then Python will always
consider the order of Parent classes in the declaration of the child class.
Output:
Parent Method class C(P1, P2):  P1 method will be considered
Child1 Method class C(P2, P1):  P2 method will be considered
Parent Method
Child2 Method 1) class P1:
2) def m1(self):
3) print("Parent1 Method")
4) Multiple Inheritance: 4) class P2:
The concept of inheriting the properties from multiple classes into a single class at a 5) def m1(self):
time, is known as multiple inheritance. 6) print("Parent2 Method")
7) class C(P1,P2):
8) def m2(self):
P1 P2 9) print("Child Method")
10) c=C()
11) c.m1()
12) c.m2()

Output:
C Parent1 Method
Child Method
Multiple
Inheritance

1) class P1:
2) def m1(self):
3) print("Parent1 Method")
4) class P2:
5) def m2(self):
6) print("Parent2 Method")
7) class C(P1,P2):
8) def m3(self):
9) print("Child2 Method")

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
43  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
44  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) Hybrid Inheritance:
Combination of Single, Multi level, multiple and Hierarchical inheritance is known as A
Hybrid Inheritance.

A B C
B

D Method Resolution Order (MRO):


 In Hybrid Inheritance the method resolution order is decided based on MRO
algorithm.
 This algorithm is also known as C3 algorithm.
E
 Samuele Pedroni proposed this algorithm.
 It follows DLR (Depth First Left to Right) i.e Child will get more priority than Parent.
 Left Parent will get more priority than Right Parent.
F  MRO(X) = X+Merge(MRO(P1),MRO(P2),...,ParentList)

G H
Head Element vs Tail Terminology:
 Assume C1,C2,C3,...are classes.
 In the list: C1C2C3C4C5....
 C1 is considered as Head Element and remaining is considered as Tail.
6) Cyclic Inheritance:
The concept of inheriting properties from one class to another class in cyclic way, is
called Cyclic inheritance.Python won't support for Cyclic Inheritance of course it is How to find Merge:
really not required.  Take the head of first list
Eg - 1: class A(A):pass  If the head is not in the tail part of any other list, then add this head to the result and
NameError: name 'A' is not defined remove it from the lists in the merge.
 If the head is present in the tail part of any other list, then consider the head element
of the next list and continue the same process.

Note: We can find MRO of any class by using mro() function.


A
print(ClassName.mro())

Eg - 2:

1) class A(B):
2) pass
3) class B(A):
4) pass

NameError: name 'B' is not defined

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
45  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
46  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Demo Program-1 for Method Resolution Order: Demo Program-2 for Method Resolution Order:

A Object

C A B C
B

D X Y
mro(A) = A, object
mro(B) = B, A, object
mro(C) = C, A, object
mro(D) = D, B, C, A, object mro(A)=A,object P
mro(B)=B,object
test.py mro(C)=C,object
mro(X)=X,A,B,object
1) class A:pass mro(Y)=Y,B,C,object
2) class B(A):pass mro(P)=P,X,A,Y,B,C,object
3) class C(A):pass
4) class D(B,C):pass
5) print(A.mro()) Finding mro(P) by using C3 Algorithm:
6) print(B.mro())
7) print(C.mro()) Formula: MRO(X) = X+Merge(MRO(P1),MRO(P2),...,ParentList)
8) print(D.mro()) mro(p) = P+Merge(mro(X),mro(Y),mro(C),XYC)
= P+Merge(XABO,YBCO,CO,XYC)
Output: = P+X+Merge(ABO,YBCO,CO,YC)
[<class '__main__.A'>, <class 'object'>] = P+X+A+Merge(BO,YBCO,CO,YC)
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>] = P+X+A+Y+Merge(BO,BCO,CO,C)
[<class '__main__.C'>, <class '__main__.A'>, <class 'object'>] = P+X+A+Y+B+Merge(O,CO,CO,C)
[<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, = P+X+A+Y+B+C+Merge(O,O,O)
<class 'object'>] = P+X+A+Y+B+C+O

test.py

1) class A:pass
2) class B:pass
3) class C:pass
4) class X(A,B):pass
5) class Y(B,C):pass
6) class P(X,Y,C):pass
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
47  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
48  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
7) print(A.mro())#AO Demo Program-3 for Method Resolution Order:
8) print(X.mro())#XABO
9) print(Y.mro())#YBCO
10) print(P.mro())#PXAYBCO Object

Output:
[<class '__main__.A'>, <class 'object'>]
[<class '__main__.X'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>] F
[<class '__main__.Y'>, <class '__main__.B'>, <class '__main__.C'>, <class 'object'>] D E
[<class '__main__.P'>, <class '__main__.X'>, <class '__main__.A'>, <class '__main__.Y'>,
<class '__main__.B'>,
<class '__main__.C'>, <class 'object'>]
B C
test.py

1) class A:
2) def m1(self):
3) print('A class Method') A
4) class B:
5) def m1(self):
6) print('B class Method') mro(o) = object
7) class C: mro(D) = D,object
8) def m1(self): mro(E) = E,object
9) print('C class Method') mro(F) = F,object
10) class X(A,B): mro(B) = B,D,E,object
11) def m1(self): mro(C) = C,D,F,object
12) print('X class Method') mro(A) = A+Merge(mro(B),mro(C),BC)
13) class Y(B,C): = A+Merge(BDEO,CDFO,BC)
14) def m1(self): = A+B+Merge(DEO,CDFO,C)
15) print('Y class Method') = A+B+C+Merge(DEO,DFO)
16) class P(X,Y,C): = A+B+C+D+Merge(EO,FO)
17) def m1(self): = A+B+C+D+E+Merge(O,FO)
18) print('P class Method') = A+B+C+D+E+F+Merge(O,O)
19) p=P() = A+B+C+D+E+F+O
20) p.m1()
test.py
Output: P class Method
1) class D:pass
2) class E:pass
In the above example P class m1() method will be considered.If P class does not contain
m1() method then as per MRO, X class method will be considered. If X class does not 3) class F:pass
contain then A class method will be considered and this process will be continued. 4) class B(D,E):pass
5) class C(D,F):pass
The method resolution in the following order: PXAYBCO 6) class A(B,C):pass
7) print(D.mro())
8) print(B.mro())

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
49  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
50  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
9) print(C.mro()) In the above program we are using super() method to call parent class constructor and
10) print(A.mro()) display() method

Output: Demo Program-2 for super():


[<class '__main__.D'>, <class 'object'>]
[<class '__main__.B'>, <class '__main__.D'>, <class '__main__.E'>, <class 'object'>] 1) class P:
[<class '__main__.C'>, <class '__main__.D'>, <class '__main__.F'>, <class 'object'>] 2) a=10
[<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.D'>, 3) def __init__(self):
<class '__main__.E'>, 4) self.b=10
<class '__main__.F'>, <class 'object'>] 5) def m1(self):
6) print('Parent instance method')
super() Method: 7) @classmethod
super() is a built-in method which is useful to call the super class constructors,variables 8) def m2(cls):
and methods from the child class. 9) print('Parent class method')
10) @staticmethod
11) def m3():
Demo Program-1 for super(): 12) print('Parent static method')
13)
1) class Person: 14) class C(P):
2) def __init__(self,name,age): 15) a=888
3) self.name=name 16) def __init__(self):
4) self.age=age 17) self.b=999
5) def display(self): 18) super().__init__()
6) print('Name:',self.name) 19) print(super().a)
7) print('Age:',self.age) 20) super().m1()
8) 21) super().m2()
9) class Student(Person): 22) super().m3()
10) def __init__(self,name,age,rollno,marks): 23)
11) super().__init__(name,age) 24) c=C()
12) self.rollno=rollno
13) self.marks=marks Output:
14)
10
15) def display(self):
Parent instance method
16) super().display()
Parent class method
17) print('Roll No:',self.rollno)
Parent static method
18) print('Marks:',self.marks)
19)
In the above example we are using super() to call various members of Parent class.
20) s1=Student('Durga',22,101,90)
21) s1.display()

Output:
Name: Durga
Age: 22
Roll No: 101
Marks: 90

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
51  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
52  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
8) print(super().a)#valid
How to Call Method of a Particular Super Class: 9) print(self.b)#valid
We can use the following approaches 10) print(super().b)#invalid
11) c=C()
1) super(D, self).m1() 12) c.m1()
It will call m1() method of super class of D.
Output:
2) A.m1(self) 10
It will call A class m1() method 20
AttributeError: 'super' object has no attribute 'b'
1) class A:
2) def m1(self): Case-2: From child class constructor and instance method, we can access parent class
3) print('A class Method')
instance method, static method and class method by using super()
4) class B(A):
5) def m1(self): 1) class P:
6) print('B class Method') 2) def __init__(self):
7) class C(B): 3) print('Parent Constructor')
8) def m1(self): 4) def m1(self):
9) print('C class Method') 5) print('Parent instance method')
10) class D(C): 6) @classmethod
11) def m1(self): 7) def m2(cls):
12) print('D class Method') 8) print('Parent class method')
13) class E(D): 9) @staticmethod
14) def m1(self): 10) def m3():
15) A.m1(self) 11) print('Parent static method')
16) 12)
17) e=E() 13) class C(P):
18) e.m1() 14) def __init__(self):
15) super().__init__()
Output: A class Method 16) super().m1()
17) super().m2()
Various Important Points about super(): 18) super().m3()
19)
Case-1: From child class we are not allowed to access parent class instance variables by 20) def m1(self):
21) super().__init__()
using super(), Compulsory we should use self only.
But we can access parent class static variables by using super(). 22) super().m1()
23) super().m2()
1) class P: 24) super().m3()
2) a=10 25)
3) def __init__(self): 26) c=C()
4) self.b=20 27) c.m1()
5)
6) class C(P):
7) def m1(self):

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
53  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
54  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output: From Class Method of Child Class, how to call Parent Class Instance Methods
Parent Constructor and Constructors:
Parent instance method
Parent class method 1) class A:
Parent static method 2) def __init__(self):
Parent Constructor 3) print('Parent constructor')
Parent instance method 4)
Parent class method 5) def m1(self):
Parent static method 6) print('Parent instance method')
7)
Case-3: From child class, class method we cannot access parent class instance methods 8) class B(A):
and constructors by using super() directly(but indirectly possible). But we can access 9) @classmethod
parent class static and class methods. 10) def m2(cls):
11) super(B,cls).__init__(cls)
1) class P: 12) super(B,cls).m1(cls)
2) def __init__(self): 13)
3) print('Parent Constructor') 14) B.m2()
4) def m1(self):
5) print('Parent instance method') Output:
6) @classmethod Parent constructor
7) def m2(cls): Parent instance method
8) print('Parent class method')
9) @staticmethod Case-4: In child class static method we are not allowed to use super() generally (But in
10) def m3(): special way we can use)
11) print('Parent static method')
12) 1) class P:
13) class C(P): 2) def __init__(self):
14) @classmethod 3) print('Parent Constructor')
15) def m1(cls): 4) def m1(self):
16) #super().__init__()--->invalid 5) print('Parent instance method')
17) #super().m1()--->invalid 6) @classmethod
18) super().m2() 7) def m2(cls):
19) super().m3() 8) print('Parent class method')
20) 9) @staticmethod
21) C.m1() 10) def m3():
11) print('Parent static method')
Output: 12)
Parent class method 13) class C(P):
Parent static method 14) @staticmethod
15) def m1():
16) super().m1()-->invalid
17) super().m2()--->invalid
18) super().m3()--->invalid
19)
20) C.m1()
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
55  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
56  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
RuntimeError: super(): no arguments

How to Call Parent Class Static Method from Child Class Static
Method by using super():
1) class A:
2)
3) @staticmethod
4) def m1():
5) print('Parent static method')
6)
7) class B(A):
8) @staticmethod

OOP’s
9) def m2():
10) super(B,B).m1()
11)
12) B.m2()

Output: Parent static method

Part - 3
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
57  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
58  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
POLYMORPHISM
1) class Duck:
2) def talk(self):
3) print('Quack.. Quack..')
4)
5) class Dog:
6) def talk(self):
poly means many. Morphs means forms.
7) print('Bow Bow..')
Polymorphism means 'Many Forms'.
8)
9) class Cat:
Eg1: Yourself is best example of polymorphism.In front of Your parents You will have one
10) def talk(self):
type of behaviour and with friends another type of behaviour.Same person but different
11) print('Moew Moew ..')
behaviours at different places,which is nothing but polymorphism.
12)
Eg2: + operator acts as concatenation and arithmetic addition 13) class Goat:
14) def talk(self):
Eg3: * operator acts as multiplication and repetition operator 15) print('Myaah Myaah ..')
16)
Eg4: The Same method with different implementations in Parent class and child 17) def f1(obj):
classes.(overriding) 18) obj.talk()
19)
Related to Polymorphism the following 4 topics are important 20) l=[Duck(),Cat(),Dog(),Goat()]
21) for obj in l:
1) Duck Typing Philosophy of Python 22) f1(obj)

2) Overloading Output:
1) Operator Overloading Quack.. Quack..
2) Method Overloading Moew Moew ..
3) Constructor Overloading Bow Bow..
Myaah Myaah ..
3) Overriding
1) Method Overriding The problem in this approach is if obj does not contain talk() method then we will get
2) Constructor Overriding AttributeError.

1) class Duck:
1) Duck Typing Philosophy of Python: 2) def talk(self):
In Python we cannot specify the type explicitly. Based on provided value at 3) print('Quack.. Quack..')
runtime the type will be considered automatically. Hence Python is considered as 4)
Dynamically Typed Programming Language. 5) class Dog:
6) def bark(self):
def f1(obj): 7) print('Bow Bow..')
obj.talk() 8) def f1(obj):
9) obj.talk()
What is the Type of obj? We cannot decide at the Beginning. At Runtime we 10)
can Pass any Type. Then how we can decide the Type? 11) d=Duck()
At runtime if 'it walks like a duck and talks like a duck,it must be duck'. Python follows this 12) f1(d)
principle. This is called Duck Typing Philosophy of Python. 13)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
59  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
60  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
14) d=Dog() 27) Myaah Myaah Myaah...
15) f1(d)

Output:
2) Overloading
D:\durga_classes>py test.py We can use same operator or methods for different purposes.
Quack.. Quack..
Traceback (most recent call last): Eg 1: + operator can be used for Arithmetic addition and String concatenation
File "test.py", line 22, in <module> print(10+20)#30
f1(d) print('durga'+'soft')#durgasoft
File "test.py", line 13, in f1
Eg 2: * operator can be used for multiplication and string repetition purposes.
obj.talk()
print(10*20)#200
AttributeError: 'Dog' object has no attribute 'talk'
print('durga'*3)#durgadurgadurga
But we can solve this problem by using hasattr() function.
Eg 3: We can use deposit() method to deposit cash or cheque or dd
deposit(cash)
hasattr(obj,'attributename')  attributename can be Method Name OR Variable Name
deposit(cheque)
deposit(dd)
Demo Program with hasattr() Function:
There are 3 types of Overloading
1) class Duck: 1) Operator Overloading
2) def talk(self): 2) Method Overloading
3) print('Quack.. Quack..') 3) Constructor Overloading
4)
5) class Human:
6) def talk(self): 1) Operator Overloading:
7) print('Hello Hi...')  We can use the same operator for multiple purposes, which is nothing but operator
8) overloading.
9) class Dog:  Python supports operator overloading.
10) def bark(self):
11) print('Bow Bow..') Eg 1: + operator can be used for Arithmetic addition and String concatenation
12) print(10+20)#30
13) def f1(obj): print('durga'+'soft')#durgasoft
14) if hasattr(obj,'talk'):
15) obj.talk() Eg 2: * operator can be used for multiplication and string repetition purposes.
16) elif hasattr(obj,'bark'): print(10*20)#200
17) obj.bark() print('durga'*3)#durgadurgadurga
18)
19) d=Duck() Demo program to use + operator for our class objects:
20) f1(d)
21) 1) class Book:
22) h=Human() 2) def __init__(self,pages):
23) f1(h) 3) self.pages=pages
24) 4)
25) d=Dog() 5) b1=Book(100)
26) f1(d)
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
61  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
62  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
6) b2=Book(200) 13) %=  object.__imod__(self,other)
7) print(b1+b2) 14) **=  object.__ipow__(self,other)
15) < 
object.__lt__(self,other)
D:\durga_classes>py test.py 16) <= 
 object.__le__(self,other)
Traceback (most recent call last): 17) > object.__gt__(self,other)

File "test.py", line 7, in <module> 18) >= object.__ge__(self,other)

print(b1+b2) 19) ==  object.__eq__(self,other)
TypeError: unsupported operand type(s) for +: 'Book' and 'Book' 20) !=  object.__ne__(self,other)

⚽ We can overload + operator to work with Book objects also. i.e Python supports Overloading > and <= Operators for Student Class Objects:
Operator Overloading.
⚽ For every operator Magic Methods are available. To overload any operator we have to 1) class Student:
override that Method in our class. 2) def __init__(self,name,marks):
⚽ Internally + operator is implemented by using __add__() method.This method is called 3) self.name=name
magic method for + operator. We have to override this method in our class. 4) self.marks=marks
5) def __gt__(self,other):
Demo Program to Overload + Operator for Our Book Class Objects: 6) return self.marks>other.marks
7) def __le__(self,other):
1) class Book: 8) return self.marks<=other.marks
2) def __init__(self,pages): 9)
3) self.pages=pages 10) print("10>20 =",10>20)
4) 11) s1=Student("Durga",100)
5) def __add__(self,other): 12) s2=Student("Ravi",200)
6) return self.pages+other.pages 13) print("s1>s2=",s1>s2)
7) 14) print("s1<s2=",s1<s2)
8) b1=Book(100) 15) print("s1<=s2=",s1<=s2)
9) b2=Book(200) 16) print("s1>=s2=",s1>=s2)
10) print('The Total Number of Pages:',b1+b2)
Output
Output: The Total Number of Pages: 300 10>20 = False
s1>s2= False
The following is the list of operators and corresponding magic methods. s1<s2= True
s1<=s2= True
1) +  object.__add__(self,other) s1>=s2= False
2) -  object.__sub__(self,other)
3) *  object.__mul__(self,other) Program to Overload Multiplication Operator to Work on Employee Objects:
4) /  object.__div__(self,other)
5) //  object.__floordiv__(self,other) 1) class Employee:
 object.__mod__(self,other)
6) % 2) def __init__(self,name,salary):
 object.__pow__(self,other)
7) **  3) self.name=name
8) +=  object.__iadd__(self,other) 4) self.salary=salary
9) -=  object.__isub__(self,other) 5) def __mul__(self,other):
10) *=  object.__imul__(self,other) 6) return self.salary*other.days
11) /=  object.__idiv__(self,other) 7)
12) //=  object.__ifloordiv__(self,other)
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
63  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
64  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
8) class TimeSheet: Demo Program with Default Arguments:
9) def __init__(self,name,days):
10) self.name=name
1) class Test:
11) self.days=days
2) def sum(self,a=None,b=None,c=None):
12)
3) if a!=None and b!= None and c!= None:
13) e=Employee('Durga',500)
4) print('The Sum of 3 Numbers:',a+b+c)
14) t=TimeSheet('Durga',25)
5) elif a!=None and b!= None:
15) print('This Month Salary:',e*t)
6) print('The Sum of 2 Numbers:',a+b)
7) else:
Output: This Month Salary: 12500 8) print('Please provide 2 or 3 arguments')
9) t=Test()
2) Method Overloading: 10) t.sum(10,20)
 If 2 methods having same name but different type of arguments then those methods 11) t.sum(10,20,30)
are said to be overloaded methods. 12) t.sum(10)
Eg: m1(int a)
m1(double d) Output
The Sum of 2 Numbers: 30
 But in Python Method overloading is not possible. The Sum of 3 Numbers: 60
 If we are trying to declare multiple methods with same name and different number of Please provide 2 or 3 arguments
arguments then Python will always consider only last method.
Demo Program with Variable Number of Arguments:
Demo Program:
1) class Test:
1) class Test: 2) def sum(self,*a):
2) def m1(self): 3) total=0
3) print('no-arg method') 4) for x in a:
4) def m1(self,a): 5) total=total+x
5) print('one-arg method') 6) print('The Sum:',total)
6) def m1(self,a,b): 7)
7) print('two-arg method') 8) t=Test()
8) 9) t.sum(10,20)
9) t=Test() 10) t.sum(10,20,30)
10) #t.m1() 11) t.sum(10)
11) #t.m1(10) 12) t.sum()
12) t.m1(10,20)
3) Constructor Overloading:
Output: two-arg method
⚽ Constructor overloading is not possible in Python.
⚽ If we define multiple constructors then the last constructor will be considered.
In the above program python will consider only last method.
1) class Test:
How we can handle Overloaded Method Requirements in Python: 2) def __init__(self):
Most of the times, if method with variable number of arguments required then we can 3) print('No-Arg Constructor')
handle with default arguments or with variable number of argument methods. 4)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
65  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
66  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) def __init__(self,a): Output:
6) print('One-Arg constructor') Constructor with variable number of arguments
7) Constructor with variable number of arguments
8) def __init__(self,a,b): Constructor with variable number of arguments
9) print('Two-Arg constructor') Constructor with variable number of arguments
10) #t1=Test() Constructor with variable number of arguments
11) #t1=Test(10)
12) t1=Test(10,20)

Output: Two-Arg constructor


3) Overriding
 In the above program only Two-Arg Constructor is available.
 But based on our requirement we can declare constructor with default arguments and Method Overriding
variable number of arguments. ⚽ What ever members available in the parent class are bydefault available to the child
class through inheritance. If the child class not satisfied with parent class
Constructor with Default Arguments: implementation then child class is allowed to redefine that method in the child class
based on its requirement. This concept is called overriding.
1) class Test: ⚽ Overriding concept applicable for both methods and constructors.
2) def __init__(self,a=None,b=None,c=None):
3) print('Constructor with 0|1|2|3 number of arguments') Demo Program for Method Overriding:
4)
5) t1=Test() 1) class P:
6) t2=Test(10) 2) def property(self):
7) t3=Test(10,20) 3) print('Gold+Land+Cash+Power')
8) t4=Test(10,20,30) 4) def marry(self):
5) print('Appalamma')
Output 6) class C(P):
Constructor with 0|1|2|3 number of arguments 7) def marry(self):
Constructor with 0|1|2|3 number of arguments 8) print('Katrina Kaif')
Constructor with 0|1|2|3 number of arguments 9)
Constructor with 0|1|2|3 number of arguments 10) c=C()
11) c.property()
12) c.marry()
Constructor with Variable Number of Arguments:
1) class Test: Output
2) def __init__(self,*a): Gold+Land+Cash+Power
3) print('Constructor with variable number of arguments') Katrina Kaif
4)
5) t1=Test() From Overriding method of child class,we can call parent class method also by using
6) t2=Test(10) super() method.
7) t3=Test(10,20)
1) class P:
8) t4=Test(10,20,30)
9) t5=Test(10,20,30,40,50,60) 2) def property(self):
3) print('Gold+Land+Cash+Power')

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
67  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
68  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
4) def marry(self): 9) self.eno=eno
5) print('Appalamma') 10) self.esal=esal
6) class C(P): 11)
7) def marry(self): 12) def display(self):
8) super().marry() 13) print('Employee Name:',self.name)
9) print('Katrina Kaif') 14) print('Employee Age:',self.age)
10) 15) print('Employee Number:',self.eno)
11) c=C() 16) print('Employee Salary:',self.esal)
12) c.property() 17)
13) c.marry() 18) e1=Employee('Durga',48,872425,26000)
19) e1.display()
Output 20) e2=Employee('Sunny',39,872426,36000)
Gold+Land+Cash+Power 21) e2.display()
Appalamma
Katrina Kaif Output
Employee Name: Durga
Demo Program for Constructor Overriding: Employee Age: 48
Employee Number: 872425
1) class P: Employee Salary: 26000
2) def __init__(self):
3) print('Parent Constructor') Employee Name: Sunny
4) Employee Age: 39
5) class C(P): Employee Number: 872426
6) def __init__(self): Employee Salary: 36000
7) print('Child Constructor')
8)
9) c=C()

Output: Child Constructor


In the above example,if child class does not contain constructor then parent class
constructor will be executed

From child class constuctor we can call parent class constructor by using super() method.

Demo Program to call Parent Class Constructor by using super():


1) class Person:
2) def __init__(self,name,age):
3) self.name=name
4) self.age=age
5)
6) class Employee(Person):
7) def __init__(self,name,age,eno,esal):
8) super().__init__(name,age)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
69  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
70  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Agenda
1) Abstract Method
2) Abstract class
3) Interface
4) Public,Private and Protected Members
5) __str__() Method
6) Difference between str() and repr() functions
7) Small Banking Application

Abstract Method:

OOP’s
 Sometimes we don't know about implementation, still we can declare a method. Such
types of methods are called abstract methods.i.e abstract method has only declaration
but not implementation.
 In python we can declare abstract method by using @abstractmethod decorator as
follows.

 @abstractmethod
 def m1(self): pass

 @abstractmethod decorator present in abc module. Hence compulsory we should


import abc module,otherwise we will get error.

Part - 4
 abc  abstract base class module

1) class Test:
2) @abstractmethod
3) def m1(self):
4) pass

NameError: name 'abstractmethod' is not defined

Eg:

1) from abc import *


2) class Test:
3) @abstractmethod
4) def m1(self):
5) pass

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
71  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
72  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Eg: 6)
7) t=Test()
1) from abc import *
2) class Fruit: TypeError: Can't instantiate abstract class Test with abstract methods m1
3) @abstractmethod
4) def taste(self): Case-4:
5) pass
1) from abc import *
Child classes are responsible to provide implemention for parent class abstract methods. 2) class Test:
3) @abstractmethod
4) def m1(self):
Abstract class: 5) pass
Some times implementation of a class is not complete,such type of partially 6)
implementation classes are called abstract classes. Every abstract class in Python should 7) t=Test()
be derived from ABC class which is present in abc module.
We can create object even class contains abstract method b'z we are not extending ABC
Case-1: class.

1) from abc import * Case-5:


2) class Test:
3) pass 1) from abc import *
4) 2) class Test:
5) t=Test() 3) @abstractmethod
4) def m1(self):
In the above code we can create object for Test class b'z it is concrete class and it does not 5) print('Hello')
conatin any abstract method. 6)
7) t=Test()
Case-2: 8) t.m1()

1) from abc import * Output: Hello


2) class Test(ABC):
3) pass Conclusion: If a class contains atleast one abstract method and if we are extending ABC
4) class then instantiation is not possible.
5) t=Test()
"abstract class with abstract method instantiation is not possible"
In the above code we can create object, even it is derived from ABC class,b'z it does not
contain any abstract method.
Parent class abstract methods should be implemented in the child classes. Otherwise we
cannot instantiate child class.If we are not creating child class object then we won't get
Case-3: any error.
1) from abc import *
Case-1:
2) class Test(ABC):
3) @abstractmethod
1) from abc import *
4) def m1(self):
2) class Vehicle(ABC):
5) pass
3) @abstractmethod

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
73  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
74  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
4) def noofwheels(self):
5) pass
Interfaces In Python:
6) In general if an abstract class contains only abstract methods such type of abstract class is
7) class Bus(Vehicle): pass considered as interface.

It is valid because we are not creating Child class object. 1) from abc import *
2) class DBInterface(ABC):
Case-2: 3) @abstractmethod
4) def connect(self):pass
1) from abc import * 5)
2) class Vehicle(ABC): 6) @abstractmethod
3) @abstractmethod 7) def disconnect(self):pass
4) def noofwheels(self): 8)
5) pass 9) class Oracle(DBInterface):
6) 10) def connect(self):
7) class Bus(Vehicle): pass 11) print('Connecting to Oracle Database...')
8) b=Bus() 12) def disconnect(self):
13) print('Disconnecting to Oracle Database...')
TypeError: Can't instantiate abstract class Bus with abstract methods noofwheels 14)
15) class Sybase(DBInterface):
Note: If we are extending abstract class and does not override its abstract method then 16) def connect(self):
child class is also abstract and instantiation is not possible. 17) print('Connecting to Sybase Database...')
18) def disconnect(self):
1) from abc import * 19) print('Disconnecting to Sybase Database...')
2) class Vehicle(ABC): 20)
3) @abstractmethod 21) dbname=input('Enter Database Name:')
4) def noofwheels(self): 22) classname=globals()[dbname]
5) pass 23) x=classname()
6) 24) x.connect()
7) class Bus(Vehicle): 25) x.disconnect()
8) def noofwheels(self):
9) return 7 D:\durga_classes>py test.py
10) Enter Database Name:Oracle
11) class Auto(Vehicle): Connecting to Oracle Database...
Disconnecting to Oracle Database...
12) def noofwheels(self):
13) return 3
D:\durga_classes>py test.py
14) b=Bus()
Enter Database Name:Sybase
15) print(b.noofwheels())#7
16) Connecting to Sybase Database...
17) a=Auto() Disconnecting to Sybase Database...
18) print(a.noofwheels())#3
Note: The inbuilt function globals()[str] converts the string 'str' into a class name and
returns the classname.
Note: Abstract class can contain both abstract and non-abstract methods also.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
75  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
76  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Demo Program-2: Reading class name from the file Concreate class vs Abstract Class vs Inteface:
1) If we dont know anything about implementation just we have requirement
config.txt specification then we should go for interface.
EPSON
2) If we are talking about implementation but not completely then we should go for
abstract class. (partially implemented class).
test.py 3) If we are talking about implementation completely and ready to provide service then
we should go for concrete class.
1) from abc import *
2) class Printer(ABC): 1) from abc import *
3) @abstractmethod 2) class CollegeAutomation(ABC):
4) def printit(self,text):pass 3) @abstractmethod
5) 4) def m1(self): pass
6) @abstractmethod 5) @abstractmethod
7) def disconnect(self):pass 6) def m2(self): pass
8) 7) @abstractmethod
9) class EPSON(Printer): 8) def m3(self): pass
10) def printit(self,text): 9) class AbsCls(CollegeAutomation):
11) print('Printing from EPSON Printer...') 10) def m1(self):
12) print(text) 11) print('m1 method implementation')
13) def disconnect(self): 12) def m2(self):
14) print('Printing completed on EPSON Printer...') 13) print('m2 method implementation')
15) 14)
16) class HP(Printer): 15) class ConcreteCls(AbsCls):
17) def printit(self,text): 16) def m3(self):
18) print('Printing from HP Printer...') 17) print('m3 method implemnentation')
19) print(text) 18)
20) def disconnect(self): 19) c=ConcreteCls()
21) print('Printing completed on HP Printer...') 20) c.m1()
22) 21) c.m2()
23) with open('config.txt','r') as f: 22) c.m3()
24) pname=f.readline()
25)
26) classname=globals()[pname] Public, Protected and Private Attributes:
27) x=classname()
28) x.printit('This data has to print...') By default every attribute is public. We can access from anywhere either within the class
29) x.disconnect() or from outside of the class.
Eg: name = 'durga'
Output:
Printing from EPSON Printer... Protected attributes can be accessed within the class anywhere but from outside of the
This data has to print... class only in child classes. We can specify an attribute as protected by prefexing with _
Printing completed on EPSON Printer... symbol.

Syntax: _variablename = value


Eg: _name='durga'

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
77  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
78  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
But is is just convention and in reality does not exists protected attributes. 5) t=Test()
6) print(t._Test__x)#10
private attributes can be accessed only within the class.i.e from outside of the class we
cannot access. We can declare a variable as private explicitly by prefexing with 2
underscore symbols.
__str__() method:
 Whenever we are printing any object reference internally __str__() method will be
syntax: __variablename=value called which is returns string in the following format
<__main__.classname object at 0x022144B0>
Eg: __name='durga'
 To return meaningful string representation we have to override __str__() method.
1) class Test:
2) x=10 1) class Student:
3) _y=20 2) def __init__(self,name,rollno):
4) __z=30 3) self.name=name
5) def m1(self): 4) self.rollno=rollno
6) print(Test.x) 5)
7) print(Test._y) 6) def __str__(self):
8) print(Test.__z) 7) return 'This is Student with Name:{} and Rollno:{}'.format(self.name,self.rollno)
9) 8)
10) t=Test() 9) s1=Student('Durga',101)
11) t.m1() 10) s2=Student('Ravi',102)
12) print(Test.x) 11) print(s1)
13) print(Test._y) 12) print(s2)
14) print(Test.__z)
Output without Overriding str():
Output:
<__main__.Student object at 0x022144B0>
10
<__main__.Student object at 0x022144D0>
20
30
10 Output with Overriding str():
20 This is Student with Name: Durga and Rollno: 101
Traceback (most recent call last): This is Student with Name: Ravi and Rollno: 102
File "test.py", line 14, in <module>
print(Test.__z) Difference between str() and repr()
AttributeError: type object 'Test' has no attribute '__z' OR
Difference between __str__() and __repr__()
How to Access Private Variables from Outside of the Class:  str() internally calls __str__() function and hence functionality of both is same.
We cannot access private variables directly from outside of the class.  Similarly,repr() internally calls __repr__() function and hence functionality of both is
But we can access indirectly as follows objectreference._classname__variablename same.
 str() returns a string containing a nicely printable representation object.
1) class Test:  The main purpose of str() is for readability.It may not possible to convert result string
2) def __init__(self): to original object.
3) self.__x=10
4)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
79  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
80  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) import datetime 11) if self.balance-amount >= self.min_balance:
2) today=datetime.datetime.now() 12) self.balance -=amount
3) s=str(today)#converting datetime object to str 13) else:
4) print(s) 14) print("Sorry, Insufficient Funds")
5) d=eval(s)#converting str object to datetime 15)
16) def printStatement(self):
D:\durgaclasses>py test.py 17) print("Account Balance:",self.balance)
2018-05-18 22:48:19.890888 18)
Traceback (most recent call last): 19) class Current(Account):
File "test.py", line 5, in <module> 20) def __init__(self,name,balance):
d=eval(s)#converting str object to datetime 21) super().__init__(name,balance,min_balance=-1000)
File "<string>", line 1 22) def __str__(self):
2018-05-18 22:48:19.890888 23) return "{}'s Current Account with Balance :{}".format(self.name,self.balance)
^ 24)
SyntaxError: invalid token 25) class Savings(Account):
26) def __init__(self,name,balance):
But repr() returns a string containing a printable representation of object. 27) super().__init__(name,balance,min_balance=0)
The main goal of repr() is unambigouous. We can convert result string to original object by 28) def __str__(self):
using eval() function,which may not possible in str() function. 29) return "{}'s Savings Account with Balance :{}".format(self.name,self.balance)
30)
1) import datetime 31) c=Savings("Durga",10000)
2) today=datetime.datetime.now() 32) print(c)
3) s=repr(today)#converting datetime object to str 33) c.deposit(5000)
4) print(s) 34) c.printStatement()
5) d=eval(s)#converting str object to datetime 35) c.withdraw(16000)
6) print(d) 36) c.withdraw(15000)
37) print(c)
Output: 38)
datetime.datetime(2018, 5, 18, 22, 51, 10, 875838) 39) c2=Current('Ravi',20000)
2018-05-18 22:51:10.875838 40) c2.deposit(6000)
41) print(c2)
Note: It is recommended to use repr() instead of str() 42) c2.withdraw(27000)
43) print(c2)
Mini Project: Banking Application
Output:
1) class Account: D:\durgaclasses>py test.py
2) def __init__(self,name,balance,min_balance): Durga's Savings Account with Balance :10000
3) self.name=name Account Balance: 15000
4) self.balance=balance Sorry, Insufficient Funds
5) self.min_balance=min_balance Durga's Savings Account with Balance :0
6) Ravi's Current Account with Balance :26000
7) def deposit(self,amount): Ravi's Current Account with Balance :-1000
8) self.balance +=amount
9)
10) def withdraw(self,amount):
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
81  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
82  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
In any programming language there are 2 types of errors are possible.

1) Syntax Errors
2) Runtime Errors

1) Syntax Errors:
The errors which occur because of invalid syntax are called syntax errors.

Eg 1:
x = 10
if x == 10
print("Hello")

SyntaxError: invalid syntax

EXCEPTION
Eg 2:
print "Hello"
SyntaxError: Missing parentheses in call to 'print'

Note: Programmer is responsible to correct these syntax errors. Once all syntax errors
are corrected then only program execution will be started.

HANDLING 2) Runtime Errors:




Also known as exceptions.
While executing the program if something goes wrong because of end user input or
programming logic or memory problems etc then we will get Runtime Errors.

Eg:
1) print(10/0)  ZeroDivisionError: division by zero
2) print(10/"ten")  TypeError: unsupported operand type(s) for /: 'int' and 'str'

3) x = int(input("Enter Number:"))
print(x)

D:\Python_classes>py test.py
Enter Number:ten
ValueError: invalid literal for int() with base 10: 'ten'

Note: Exception Handling concept applicable for Runtime Errors but not for syntax errors

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
83  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
84  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) print("Hello")
What is Exception? 2) print(10/0)
An unwanted and unexpected event that disturbs normal flow of program is called 3) print("Hi")
exception.
D:\Python_classes>py test.py
Eg: Hello
 ZeroDivisionError Traceback (most recent call last):
 TypeError File "test.py", line 2, in <module>
 ValueError print(10/0)
 FileNotFoundError ZeroDivisionError: division by zero
 EOFError
 SleepingError
 TyrePuncturedError Python's Exception Hierarchy
It is highly recommended to handle exceptions. The main objective of exception handling
is Graceful Termination of the program (i.e we should not block our resources and we BaseException
should not miss anything)

Exception handling does not mean repairing exception. We have to define alternative way
to continue rest of the program normally.
Exception SystemExit GeneratorExit KeyboardInterrupt
Eg: For example our programming requirement is reading data from remote file locating
at London. At runtime if London file is not available then the program should not be
terminated abnormally. We have to provide local file to continue rest of the program
normally. This way of defining alternative is nothing but exception handling. Attribute Arithmetic EOF Name Lookup OS Type Value
Error Error Error Error Error Error Error Error
try:
Read Data from Remote File locating at London. ZeroDivision Index FileNotFound
except FileNotFoundError: Error Error Error
use local file and continue rest of the program normally
FloatingPoint Key Interrupted
Q. What is an Exception? Error Error Error
Q. What is the purpose of Exception Handling?
Q. What is the meaning of Exception Handling?
Overflow Permission
Error Error
Default Exception Handing in Python:
 Every exception in Python is an object. For every exception type the corresponding TimeOut
classes are available. Error
 Whevever an exception occurs PVM will create the corresponding exception object  Every Exception in Python is a class.
and will check for handling code. If handling code is not available then Python  All exception classes are child classes of BaseException.i.e every exception class
interpreter terminates the program abnormally and prints corresponding exception extends BaseException either directly or indirectly. Hence BaseException acts as root
information to the console. for Python Exception Hierarchy.
 The rest of the program won't be executed.  Most of the times being a programmer we have to concentrate Exception and its child
classes.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
85  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
86  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Customized Exception Handling by using try-except: Case-1: If there is no exception
1,2,3,5 and Normal Termination
 It is highly recommended to handle exceptions.
 The code which may raise exception is called risky code and we have to take risky code
inside try block. The corresponding handling code we have to take inside except block.
Case-2: If an exception raised at stmt-2 and corresponding except block matched
1,4,5 Normal Termination
try:
Risky Code
except XXX: Case-3: If an exception rose at stmt-2 and corresponding except block not matched
Handling code/Alternative Code 1, Abnormal Termination

Without try-except: Case-4: If an exception rose at stmt-4 or at stmt-5 then it is always abnormal
termination.
1) print("stmt-1")
2) print(10/0)
3) print("stmt-3")
Conclusions:
1) Within the try block if anywhere exception raised then rest of the try block won’t be
executed eventhough we handled that exception. Hence we have to take only risky
Output code inside try block and length of the try block should be as less as possible.
stmt-1 2) In addition to try block, there may be a chance of raising exceptions inside except and
ZeroDivisionError: division by zero finally blocks also.
Abnormal termination/Non-Graceful Termination 3) If any statement which is not part of try block raises an exception then it is always
abnormal termination.
With try-except:

1) print("stmt-1") How to Print Exception Information:


2) try: try:
3) print(10/0)
4) except ZeroDivisionError: 1) print(10/0)
5) print(10/2) 2) except ZeroDivisionError as msg:
6) print("stmt-3") 3) print("exception raised and its description is:",msg)

Output Output exception raised and its description is: division by zero
stmt-1
5.0
stmt-3
try with Multiple except Blocks:
The way of handling exception is varied from exception to exception.Hence for every
Normal termination/Graceful Termination
exception type a seperate except block we have to provide. i.e try with multiple except
blocks is possible and recommended to use.
Control Flow in try-except:
try: Eg:
stmt-1 try:
stmt-2 -------
stmt-3 -------
except XXX: -------
stmt-4 except ZeroDivisionError:
stmt-5 perform alternative arithmetic operations

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
87  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
88  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
except FileNotFoundError: Enter Second Number: 0
use local file instead of remote file ArithmeticError

If try with multiple except blocks available then based on raised exception the Single except Block that can handle Multiple Exceptions:
corresponding except block will be executed. We can write a single except block that can handle multiple different types of exceptions.
1) try:
except (Exception1,Exception2,exception3,..): OR
2) x=int(input("Enter First Number: "))
except (Exception1,Exception2,exception3,..) as msg :
3) y=int(input("Enter Second Number: "))
4) print(x/y)
Parentheses are mandatory and this group of exceptions internally considered as tuple.
5) except ZeroDivisionError :
6) print("Can't Divide with Zero") 1) try:
7) except ValueError:
2) x=int(input("Enter First Number: "))
8) print("please provide int value only")
3) y=int(input("Enter Second Number: "))
4) print(x/y)
D:\Python_classes>py test.py
5) except (ZeroDivisionError,ValueError) as msg:
Enter First Number: 10
6) print("Plz Provide valid numbers only and problem is: ",msg)
Enter Second Number: 2
5.0
D:\Python_classes>py test.py
Enter First Number: 10
D:\Python_classes>py test.py
Enter Second Number: 0
Enter First Number: 10
Plz Provide valid numbers only and problem is: division by zero
Enter Second Number: 0
Can't Divide with Zero
D:\Python_classes>py test.py
Enter First Number: 10
D:\Python_classes>py test.py
Enter Second Number: ten
Enter First Number: 10
Plz Provide valid numbers only and problem is: invalid literal for int() with b are 10: 'ten'
Enter Second Number: ten
please provide int value only
Default except Block:
If try with multiple except blocks available then the order of these except blocks is We can use default except block to handle any type of exceptions.
important .Python interpreter will always consider from top to bottom until matched In default except block generally we can print normal error messages.
except block identified.
Syntax:
1) try: except:
2) x=int(input("Enter First Number: ")) statements
3) y=int(input("Enter Second Number: "))
4) print(x/y) 1) try:
5) except ArithmeticError : 2) x=int(input("Enter First Number: "))
6) print("ArithmeticError") 3) y=int(input("Enter Second Number: "))
7) except ZeroDivisionError: 4) print(x/y)
8) print("ZeroDivisionError") 5) except ZeroDivisionError:
6) print("ZeroDivisionError:Can't divide with zero")
D:\Python_classes>py test.py 7) except:
Enter First Number: 10 8) print("Default Except:Plz provide valid input only")

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
89  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
90  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
D:\Python_classes>py test.py finally:
Enter First Number: 10 Cleanup code
Enter Second Number: 0
ZeroDivisionError:Can't divide with zero The speciality of finally block is it will be executed always whether exception raised or not
raised and whether exception handled or not handled.
D:\Python_classes>py test.py
Enter First Number: 10 Case-1: If there is no exception
Enter Second Number: ten
Default Except:Plz provide valid input only 1) try:
2) print("try")
***Note: If try with multiple except blocks available then default except block should be 3) except:
last, otherwise we will get SyntaxError. 4) print("except")
5) finally:
1) try: 6) print("finally")
2) print(10/0)
3) except: Output
4) print("Default Except") try
5) except ZeroDivisionError: finally
6) print("ZeroDivisionError")
Case-2: If there is an exception raised but handled
SyntaxError: default 'except:' must be last
1) try:
Note: The following are various possible combinations of except blocks 2) print("try")
1) except ZeroDivisionError: 3) print(10/0)
2) except ZeroDivisionError as msg: 4) except ZeroDivisionError:
3) except (ZeroDivisionError,ValueError) : 5) print("except")
4) except (ZeroDivisionError,ValueError) as msg: 6) finally:
5) except : 7) print("finally")

finally Block: Output


try
☕ It is not recommended to maintain clean up code(Resource Deallocating Code or except
Resource Releasing code) inside try block because there is no guarentee for the finally
execution of every statement inside try block always.
☕ It is not recommended to maintain clean up code inside except block, because if there Case-3: If there is an exception raised but not handled
is no exception then except block won't be executed.
☕ Hence we required some place to maintain clean up code which should be executed 1) try:
always irrespective of whether exception raised or not raised and whether exception 2) print("try")
handled or not handled. Such type of best place is nothing but finally block. 3) print(10/0)
☕ Hence the main purpose of finally block is to maintain clean up code. 4) except NameError:
5) print("except")
try: 6) finally:
Risky Code 7) print("finally")
except:
Handling Code
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
91  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
92  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output Case-3: If an exception raised at stmt2 but the corresponding except block not matched
try 1,5 Abnormal Termination
finally
ZeroDivisionError: division by zero(Abnormal Termination) Case-4:If an exception raised at stmt4 then it is always abnormal termination but before
that finally block will be executed.
*** Note: There is only one situation where finally block won't be executed ie whenever
we are using os._exit(0) function. Case-5: If an exception raised at stmt-5 or at stmt-6 then it is always abnormal
termination
Whenever we are using os._exit(0) function then Python Virtual Machine itself will be
shutdown.In this particular case finally won't be executed.
Nested try-except-finally Blocks:
1) imports We can take try-except-finally blocks inside try or except or finally blocks.i.e nesting of try-
2) try: except-finally is possible.
3) print("try") try:
4) os._exit(0) ----------
5) except NameError: ----------
6) print("except") ----------
7) finally: try:
8) print("finally") -------------
--------------
Output: try --------------
except:
Note: --------------
--------------
os._exit(0)
--------------
Where 0 represents status code and it indicates normal termination
------------
There are multiple status codes are possible.
except:
-----------
Control Flow in try-except-finally: -----------
try: -----------
stmt-1
stmt-2 General Risky code we have to take inside outer try block and too much risky code we
stmt-3 have to take inside inner try block. Inside Inner try block if an exception raised then inner
except: except block is responsible to handle. If it is unable to handle then outer except block is
stmt-4 responsible to handle.
finally:
1) try:
stmt-5
2) print("outer try block")
stmt-6
3) try:
4) print("Inner try block")
Case-1: If there is no exception 5) print(10/0)
1,2,3,5,6 Normal Termination 6) except ZeroDivisionError:
7) print("Inner except block")
Case-2: If an exception raised at stmt2 and the corresponding except block matched 8) finally:
1,4,5,6 Normal Termination 9) print("Inner finally block")

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
93  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
94  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
10) except: Case-5: If an exception raised at stmt-5 and inner except block not matched but outer
11) print("outer except block") except block matched 1,2,3,4,8,10,11,12,Normal Termination
12) finally:
13) print("outer finally block") Case-6:If an exception raised at stmt-5 and both inner and outer except blocks are not
matched 1,2,3,4,8,11,Abnormal Termination
Output
outer try block Case-7: If an exception raised at stmt-7 and corresponding except block matched
Inner try block 1,2,3,.,.,.,8,10,11,12,Normal Termination
Inner except block
Inner finally block
Case-8: If an exception raised at stmt-7 and corresponding except block not matched
outer finally block
1,2,3,.,.,.,8,11,Abnormal Termination

Control Flow in nested try-except-finally: Case-9: If an exception raised at stmt-8 and corresponding except block matched
try: 1,2,3,.,.,.,.,10,11,12 Normal Termination
stmt-1
stmt-2 Case-10: If an exception raised at stmt-8 and corresponding except block not matched
stmt-3 1,2,3,.,.,.,.,11,Abnormal Termination
try:
stmt-4 Case-11: If an exception raised at stmt-9 and corresponding except block matched
stmt-5 1,2,3,.,.,.,.,8,10,11,12,Normal Termination
stmt-6
except X:
Case-12: If an exception raised at stmt-9 and corresponding except block not matched
stmt-7
1,2,3,.,.,.,.,8,11,Abnormal Termination
finally:
stmt-8
stmt-9 Case-13: If an exception raised at stmt-10 then it is always abonormal termination but
except Y: before abnormal termination finally block(stmt-11) will be executed.
stmt-10
finally: Case-14: If an exception raised at stmt-11 or stmt-12 then it is always abnormal
stmt-11 termination.
stmt-12
Note: If the control entered into try block then compulsary finally block will be executed.
Case-1: If there is no exception If the control not entered into try block then finally block won't be executed.
1,2,3,4,5,6,8,9,11,12 Normal Termination

Case-2: If an exception raised at stmt-2 and the corresponding except block matched else Block with try-except-finally:
1,10,11,12 Normal Termination We can use else block with try-except-finally blocks.
else block will be executed if and only if there are no exceptions inside try block.
Case-3: If an exceptiion raised at stmt-2 and the corresponding except block not matched try:
1,11,Abnormal Termination Risky Code
except:
Case-4: If an exception raised at stmt-5 and inner except block matched will be executed if exception inside try
1,2,3,4,7,8,9,11,12 Normal Termination

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
95  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
96  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
else:
try:
finally:
will be executed if there is no exception inside try 1
print("try") 
will be executed whether exception raised or not raised and handled or not except:
handled
2
print("Hello") 
else:
Eg: 3
print("Hello") 
try: finally:
print("try") 4
print("Hello") 
print(10/0)  1 try:
except: print("try")
print("except") 5
except: √
else: print("except")
print("else")
try:
finally:
print("try")
print("finally") 6
finally: √
print("finally")
If we comment line-1 then else block will be executed b'z there is no exception inside try.
In this case the output is: try:
try print("try")
except:
else
finally
7
print("except") √
else:
If we are not commenting line-1 then else block won't be executed b'z there is exception print("else")
inside try block. In this case output is: try:
print("try")
try
except
8
else: 
finally print("else")
try:
print("try")
Various possible Combinations of try-except-else-finally: else:
1) Whenever we are writing try block, compulsory we should write except or finally 9
print("else") 
block.i.e without except or finally block we cannot write try block.
finally:
2) Wheneever we are writing except block, compulsory we should write try block. i.e
print("finally")
except without try is always invalid.
3) Whenever we are writing finally block, compulsory we should write try block. i.e try:
finally without try is always invalid. print("try")
except XXX:
4) We can write multiple except blocks for the same try,but we cannot write multiple
finally blocks for the same try
10
print("except-1") √
5) Whenever we are writing else block compulsory except block should be there. i.e except YYY:
without except we cannot write else block. print("except-2")
6) In try-except-else-finally order is important. try:
print("try")
7) We can define try-except-else-finally inside try, except, else and finally blocks. i.e
nesting of try-except-else-finally is always possible.
11
except : 
print("except-1")

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
97  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
98  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
else: except:
print("else") print("except")
else: try:
print("else") print("try")
try: except:
print("try") print("except")
except :
18
try: √
print("except-1") print("try")
12
finally:  finally:
print("finally") print("finally")
finally: try:
print("finally") print("try")
try: except:
print("try") print("except")
13 print("Hello")  19
if 10>20: √
except: print("if")
print("except") else:
try: print("else")
print("try") try:
except: print("try")
14 print("except")  try:
print("Hello") print("inner try")
except: except:
print("except")
20
print("inner except block") √
try: finally:
print("try") print("inner finally block")
except: except:
15 print("except")  print("except")
print("Hello") try:
finally: print("try")
print("finally")
try: except:
print("try") print("except")
except: 21 try: √
16 print("except")  print("inner try")
except:
print("Hello")
else: print("inner except block")
print("else") finally:
try: print("inner finally block")
print("try") try:
except: print("try")
17
print("except") √ 22 except: √
try: print("except")
print("try") finally:

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
99  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
100  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
try: Eg 2: Whenever we are trying to convert input value to int type and if input value is
print("inner try") not int value then Python will raise ValueError automatically
except: x=int("ten")  ValueError
print("inner except block")
finally:
print("inner finally block")
2) User Defined Exceptions:
 Also known as Customized Exceptions or Programatic Exceptions
try:
 Some time we have to define and raise exceptions explicitly to indicate that something
print("try")
goes wrong, such type of exceptions are called User Defined Exceptions or Customized
except:
Exceptions
print("except")
23
try:   Programmer is responsible to define these exceptions and Python not having any idea
about these. Hence we have to raise explicitly based on our requirement by using
print("try")
"raise" keyword.
else:
Eg:
print("else")
 InSufficientFundsException
try:  InvalidInputException
print("try")  TooYoungException
try:
24
print("inner try")   TooOldException

except:
print("except") How to Define and Raise Customized Exceptions:
try: Every exception in Python is a class that extends Exception class either directly or
print("try") indirectly.
else:
print("else") Syntax:
25
except:  class classname(predefined exception class name):
print("except") def __init__(self,arg):
finally: self.msg=arg
print("finally")
1) class TooYoungException(Exception):
2) def __init__(self,arg):
Types of Exceptions: 3) self.msg=arg
In Python there are 2 types of exceptions are possible.
1) Predefined Exceptions TooYoungException is our class name which is the child class of Exception
2) User Definded Exceptions
We can raise exception by using raise keyword as follows
raise TooYoungException("message")
1) Predefined Exceptions:
 Also known as inbuilt exceptions. 1) class TooYoungException(Exception):
 The exceptions which are raised automatically by Python virtual machine whenver a 2) def __init__(self,arg):
particular event occurs are called pre defined exceptions. 3) self.msg=arg
4)
Eg 1: Whenever we are trying to perform Division by zero, automatically Python will 5) class TooOldException(Exception):
raise ZeroDivisionError. 6) def __init__(self,arg):
print(10/0) 7) self.msg=arg
8)
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
101  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
102  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
9) age=int(input("Enter Age:"))
10) if age>60:
11) raise TooYoungException("Plz wait some more time you will get best match soon!!!")
12) elif age<18:
13) raise TooOldException("Your age already crossed marriage age...no chance of
getting marriage")
14) else:
15) print("You will get match details soon by email!!!")

D:\Python_classes>py test.py
Enter Age:90
__main__.TooYoungException: Plz wait some more time you will get best match soon!!!

FILE
D:\Python_classes>py test.py
Enter Age:12
__main__.TooOldException: Your age already crossed marriage age...no chance of g
etting marriage

D:\Python_classes>py test.py
Enter Age:27
You will get match details soon by email!!!

Note: raise keyword is best suitable for customized exceptions but not for pre defined
exceptions

HANDLING

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
103  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
104  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
 As the part of programming requirement, we have to store our data permanently for Note: All the above modes are applicable for text files. If the above modes suffixed with
future purpose. For this requirement we should go for files. 'b' then these represents for binary files.
 Files are very common permanent storage areas to store our data.
Eg: rb,wb,ab,r+b,w+b,a+b,xb
Types of Files: f = open("abc.txt","w")
There are 2 types of files
We are opening abc.txt file for writing data.

1) Text Files:
Usually we can use text files to store character data Closing a File:
Eg: abc.txt After completing our operations on the file, it is highly recommended to close the file.
For this we have to use close() function.
2) Binary Files: f.close()
Usually we can use binary files to store binary data like images,video files, audio files
etc...
Various Properties of File Object:
Once we opend a file and we got file object, we can get various details related to that file
Opening a File: by using its properties.
 Before performing any operation (like read or write) on the file,first we have to open  name  Name of opened file
that file.For this we should use Python's inbuilt function open()  mode  Mode in which the file is opened
 But at the time of open, we have to specify mode,which represents the purpose of  closed  Returns boolean value indicates that file is closed or not
opening file.  readable() Retruns boolean value indicates that whether file is readable or not
f = open(filename, mode)  writable() Returns boolean value indicates that whether file is writable or not.

The allowed modes in Python are 1) f=open("abc.txt",'w')


2) print("File Name: ",f.name)
1) r  open an existing file for read operation. The file pointer is positioned at the 3) print("File Mode: ",f.mode)
beginning of the file.If the specified file does not exist then we will get 4) print("Is File Readable: ",f.readable())
FileNotFoundError.This is default mode. 5) print("Is File Writable: ",f.writable())
6) print("Is File Closed : ",f.closed)
2) w  open an existing file for write operation. If the file already contains some data 7) f.close()
then it will be overridden. If the specified file is not already avaialble then this mode will 8) print("Is File Closed : ",f.closed)
create that file.
Output
3) a  open an existing file for append operation. It won't override existing data.If the D:\Python_classes>py test.py
specified file is not already avaialble then this mode will create a new file. File Name: abc.txt
File Mode: w
4) r+  To read and write data into the file. The previous data in the file will not be Is File Readable: False
deleted.The file pointer is placed at the beginning of the file. Is File Writable: True
5) w+  To write and read data. It will override existing data. Is File Closed: False
Is File Closed: True
6) a+  To append and read data from the file.It wont override existing data.

7) x  To open a file in exclusive creation mode for write operation. If the file already
exists then we will get FileExistsError.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
105  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
106  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Writing Data to Text Files: Reading Character Data from Text Files:
We can write character data to the text files by using the following 2 methods. We can read character data from text file by using the following read methods.
1) write(str)
2) writelines(list of lines)  read() To read total data from the file
 read(n)  To read 'n' characters from the file
1) f=open("abcd.txt",'w')  readline() To read only one line
2) f.write("Durga\n")  readlines() To read all lines into a list
3) f.write("Software\n")
4) f.write("Solutions\n") Eg 1: To read total data from the file
5) print("Data written to the file successfully")
6) f.close() 1) f=open("abc.txt",'r')
2) data=f.read()
abcd.txt: 3) print(data)
Durga 4) f.close()
Software
Solutions Output
sunny
Note: In the above program, data present in the file will be overridden everytime if we bunny
run the program. Instead of overriding if we want append operation then we should open chinny
the file as follows. vinny

f = open("abcd.txt","a") Eg 2: To read only first 10 characters:


Eg 2:
1) f=open("abc.txt",'r')
1) f=open("abcd.txt",'w') 2) data=f.read(10)
2) list=["sunny\n","bunny\n","vinny\n","chinny"] 3) print(data)
3) f.writelines(list) 4) f.close()
4) print("List of lines written to the file successfully")
5) f.close() Output
sunny
abcd.txt: bunn
sunny
bunny Eg 3: To read data line by line:
vinny
chinny 1) f=open("abc.txt",'r')
2) line1=f.readline()
Note: While writing data by using write() methods, compulsory we have to provide line 3) print(line1,end='')
seperator(\n), otherwise total data should be written to a single line. 4) line2=f.readline()
5) print(line2,end='')
6) line3=f.readline()
7) print(line3,end='')
8) f.close()

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
107  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
108  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output 1) with open("abc.txt","w") as f:
sunny 2) f.write("Durga\n")
bunny 3) f.write("Software\n")
chinny 4) f.write("Solutions\n")
5) print("Is File Closed: ",f.closed)
Eg 4: To read all lines into list: 6) print("Is File Closed: ",f.closed)

1) f=open("abc.txt",'r') Output
2) lines=f.readlines() Is File Closed: False
3) for line in lines: Is File Closed: True
4) print(line,end='')
5) f.close()
The seek() and tell() Methods:
Output
sunny tell():
bunny
 We can use tell() method to return current position of the cursor(file pointer) from
chinny
beginning of the file. [ can you plese telll current cursor position]
vinny
 The position(index) of first character in files is zero just like string index.
Eg 5: 1) f=open("abc.txt","r")
2) print(f.tell())
1) f=open("abc.txt","r") 3) print(f.read(2))
2) print(f.read(3)) 4) print(f.tell())
3) print(f.readline()) 5) print(f.read(3))
4) print(f.read(4)) 6) print(f.tell())
5) print("Remaining data")
6) print(f.read())
abc.txt:
sunny
Output bunny
sun chinny
ny vinny
bunn
Output:
Remaining data
0
y
su
chinny
2
vinny
nny
5
The with Statement:
 The with statement can be used while opening a file.We can use this to group file
operation statements within a block.
seek():
We can use seek() method to move cursor (file pointer) to specified location.
 The advantage of with statement is it will take care closing of file,after completing all
[Can you please seek the cursor to a particular location]
operations automatically even in the case of exceptions also, and we are not required
f.seek(offset, fromwhere)  offset represents the number of positions
to close explicitly.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
109  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
110  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
The allowed Values for 2nd Attribute (from where) are 7) print("File does not exist:",fname)
0  From beginning of File (Default Value) 8) sys.exit(0)
1  From Current Position 9) print("The content of file is:")
2  From end of the File 10) data=f.read()
11) print(data)
Note: Python 2 supports all 3 values but Python 3 supports only zero.
Output
1) data="All Students are STUPIDS" D:\Python_classes>py test.py
2) f=open("abc.txt","w") Enter File Name: durga.txt
3) f.write(data) File does not exist: durga.txt
4) with open("abc.txt","r+") as f: D:\Python_classes>py test.py
5) text=f.read() Enter File Name: abc.txt
6) print(text) File exists: abc.txt
7) print("The Current Cursor Position: ",f.tell()) The content of file is:
8) f.seek(17) All Students are GEMS!!!
9) print("The Current Cursor Position: ",f.tell()) All Students are GEMS!!!
10) f.write("GEMS!!!") All Students are GEMS!!!
11) f.seek(0) All Students are GEMS!!!
12) text=f.read() All Students are GEMS!!!
13) print("Data After Modification:") All Students are GEMS!!!
14) print(text)
Note:
Output sys.exit(0)  To exit system without executing rest of the program.
All Students are STUPIDS argument represents status code. 0 means normal termination and it is the default value.
The Current Cursor Position: 24
The Current Cursor Position: 17 Q) Program to print the Number of Lines, Words and Characters
Data After Modification:
All Students are GEMS!!! present in the given File?
1) import os,sys
How to check a particular File exists OR not? 2) fname=input("Enter File Name: ")
We can use os library to get information about files in our computer. 3) if os.path.isfile(fname):
os module has path sub module,which contains isFile() function to check whether a 4) print("File exists:",fname)
particular file exists or not? 5) f=open(fname,"r")
os.path.isfile(fname) 6) else:
7) print("File does not exist:",fname)
Q) Write a Program to check whether the given File exists OR not. If it is 8) sys.exit(0)
available then print its content? 9) lcount=wcount=ccount=0
10) for line in f:
1) import os,sys 11) lcount=lcount+1
2) fname=input("Enter File Name: ") 12) ccount=ccount+len(line)
3) if os.path.isfile(fname): 13) words=line.split()
4) print("File exists:",fname) 14) wcount=wcount+len(words)
5) f=open(fname,"r") 15) print("The number of Lines:",lcount)
6) else: 16) print("The number of Words:",wcount)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
111  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
112  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
17) print("The number of Characters:",ccount)
Writing Data to CSV File:
Output
1) import csv
D:\Python_classes>py test.py
2) with open("emp.csv","w",newline='') as f:
Enter File Name: durga.txt
3) w=csv.writer(f) # returns csv writer object
File does not exist: durga.txt
4) w.writerow(["ENO","ENAME","ESAL","EADDR"])
5) n=int(input("Enter Number of Employees:"))
D:\Python_classes>py test.py
6) for i in range(n):
Enter File Name: abc.txt
7) eno=input("Enter Employee No:")
File exists: abc.txt
8) ename=input("Enter Employee Name:")
The number of Lines: 6
9) esal=input("Enter Employee Salary:")
The number of Words: 24
10) eaddr=input("Enter Employee Address:")
The number of Characters: 149
11) w.writerow([eno,ename,esal,eaddr])
12) print("Total Employees data written to csv file successfully")
abc.txt
All Students are GEMS!!!
Note: Observe the difference with newline attribute and without
All Students are GEMS!!!
with open("emp.csv","w",newline='') as f:
All Students are GEMS!!!
with open("emp.csv","w") as f:
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!! Note: If we are not using newline attribute then in the csv file blank lines will be included
between data. To prevent these blank lines, newline attribute is required in Python-3,but
in Python-2 just we can specify mode as 'wb' and we are not required to use newline
Handling Binary Data: attribute.
It is very common requirement to read or write binary data like images,video files,audio
files etc.
Reading Data from CSV File:
Q) Program to read Image File and write to a New Image File?
1) import csv
2) f=open("emp.csv",'r')
1) f1=open("rossum.jpg","rb")
3) r=csv.reader(f) #returns csv reader object
2) f2=open("newpic.jpg","wb")
4) data=list(r)
3) bytes=f1.read()
5) #print(data)
4) f2.write(bytes)
6) for line in data:
5) print("New Image is available with the name: newpic.jpg")
7) for word in line:
8) print(word,"\t",end='')
Handling CSV Files: 9) print()
⚽ CSV  Comma seperated values
⚽ As the part of programming, it is very common requirement to write and read data wrt Output
csv files. Python provides csv module to handle csv files. D:\Python_classes>py test.py

ENO ENAME ESAL EADDR


100 Durga 1000 Hyd
200 Sachin 2000 Mumbai
300 Dhoni 3000 Ranchi

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
113  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
114  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
6) print("The Content of this file is:")
Zipping and Unzipping Files: 7) f1=open(name,'r')
It is very common requirement to zip and unzip files. 8) print(f1.read())
9) print()
The main advantages are:
1) To improve memory utilization
2) We can reduce transport time Working with Directories:
3) We can improve performance. It is very common requirement to perform operations for directories like
1) To know current working directory
To perform zip and unzip operations, Python contains one in-bulit module zip file. 2) To create a new directory
This module contains a class: ZipFile 3) To remove an existing directory
4) To rename a directory
5) To list contents of the directory
To Create Zip File: etc...
We have to create ZipFile class object with name of the zip file, mode and constant To perform these operations, Python provides inbuilt module os,which contains several
ZIP_DEFLATED. This constant represents we are creating zip file. functions to perform directory related operations.
f = ZipFile("files.zip","w","ZIP_DEFLATED")
Q1) To Know Current Working Directory
Once we create ZipFile object,we can add files by using write() method. import os
f.write(filename) cwd = os.getcwd()
print("Current Working Directory:",cwd)
1) from zipfile import *
2) f=ZipFile("files.zip",'w',ZIP_DEFLATED) Q2) To Create a Sub Directory in the Current Working Directory
3) f.write("file1.txt") import os
4) f.write("file2.txt") os.mkdir("mysub")
5) f.write("file3.txt") print("mysub directory created in cwd")
6) f.close()
7) print("files.zip file created successfully")
Q3) To Create a Sub Directory in mysub Directory
cwd
To perform unzip Operation: |-mysub
We have to create ZipFile object as follows |-mysub2
f = ZipFile("files.zip","r",ZIP_STORED)
import os
ZIP_STORED represents unzip operation. This is default value and hence we are not os.mkdir("mysub/mysub2")
required to specify. print("mysub2 created inside mysub")
Once we created ZipFile object for unzip operation, we can get all file names present in
that zip file by using namelist() method. Note: Assume mysub already present in cwd.
names = f.namelist()
Q4) To Create Multiple Directories like sub1 in that sub2 in that
1) from zipfile import *
2) f=ZipFile("files.zip",'r',ZIP_STORED) sub3
3) names=f.namelist() import os
4) for name in names: os.makedirs("sub1/sub2/sub3")
5) print( "File Name: ",name) print("sub1 and in that sub2 and in that sub3 directories created")

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
115  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
116  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q5) To Remove a Directory  onerror = None  On error detected which function has to execute.
import os  followlinks = True  To visit directories pointed by symbolic links
os.rmdir("mysub/mysub2")
print("mysub2 directory deleted") Eg: To display all contents of Current working directory including sub directories:

1) import os
Q6) To Remove Multiple Directories in the Path 2) for dirpath,dirnames,filenames in os.walk('.'):
import os 3) print("Current Directory Path:",dirpath)
os.removedirs("sub1/sub2/sub3") 4) print("Directories:",dirnames)
print("All 3 directories sub1,sub2 and sub3 removed") 5) print("Files:",filenames)
6) print()
Q7) To Rename a Directory
import os Output
os.rename("mysub","newdir") Current Directory Path: .
print("mysub directory renamed to newdir") Directories: ['com', 'newdir', 'pack1', '__pycache__']
Files: ['abc.txt', 'abcd.txt', 'demo.py', 'durgamath.py', 'emp.csv', 'file1.txt', 'file2.txt', 'file3.
Q8) To know Contents of Directory txt', 'files.zip', 'log.txt', 'module1.py', 'mylog.txt', 'newpic.jpg', 'rossum.jpg', 'test.py']
OS Module provides listdir() to list out the contents of the specified directory. It
Current Directory Path: .\com
won't display the contents of sub directory.
Directories: ['durgasoft', '__pycache__']
Files: ['module1.py', '__init__.py']
1) import os
...
2) print(os.listdir("."))
Note: To display contents of particular directory, we have to provide that directory name
Output
as argument to walk() function.
D:\Python_classes>py test.py
os.walk("directoryname")
['abc.py', 'abc.txt', 'abcd.txt', 'com', 'demo.py', 'durgamath.py', 'emp.csv', '
file1.txt', 'file2.txt', 'file3.txt', 'files.zip', 'log.txt', 'module1.py', 'myl
og.txt', 'newdir', 'newpic.jpg', 'pack1', 'rossum.jpg', 'test.py', '__pycache__'] Q) What is the difference between listdir() and walk() Functions?
In the case of listdir(), we will get contents of specified directory but not sub directory
 The above program display contents of current working directory but not contents of contents. But in the case of walk() function we will get contents of specified directory
sub directories. and its sub directories also.
 If we want the contents of a directory including sub directories then we should go for
walk() function. Running Other Programs from Python Program:
OS Module contains system() function to run programs and commands.
Q9) To Know Contents of Directory including Sub Directories It is exactly same as system() function in C language.
 We have to use walk() function
 [Can you please walk in the directory so that we can aware all contents of that os.system("commad string")
directory] The argument is any command which is executing from DOS.
 os.walk(path, topdown = True, onerror = None, followlinks = False)
 It returns an Iterator object whose contents can be displayed by using for loop Eg:
import os
 path  Directory Path. cwd means . os.system("dir *.py")
 topdown = True  Travel from top to bottom os.system("py abc.py")

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
117  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
118  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
How to get Information about a File: Output
File Size in Bytes: 22410
We can get statistics of a file like size, last accessed time,last modified time etc by using
File Last Accessed Time: 2017-09-15 10:27:26.599490
stat() function of os module.
File Last Modified Time: 2017-09-16 10:46:39.245394
stats = os.stat("abc.txt")

The statistics of a file includes the following parameters: Pickling and Unpickling of Objects:
 Sometimes we have to write total state of object to the file and we have to read total
1) st_mode  Protection Bits object from the file.
2) st_ino  Inode number  The process of writing state of object to the file is called pickling and the process of
3) st_dev  Device reading state of an object from the file is called unpickling.
4) st_nlink  Number of Hard Links  We can implement pickling and unpickling by using pickle module of Python.
5) st_uid  User id of Owner  pickle module contains dump() function to perform pickling. pickle.dump(object,file)
6) st_gid  Group id of Owner  pickle module contains load() function to perform unpickling obj=pickle.load(file)
7) st_size  Size of File in Bytes
8) st_atime  Time of Most Recent Access
9) st_mtime  Time of Most Recent Modification pickling
10) st_ctime  Time of Most Recent Meta Data Change pickle.dump
eno: 100 (e1, f)
Note: st_atime, st_mtime and st_ctime returns the time as number of milli seconds since ename: Durga
Jan 1st 1970, 12:00 AM. By using datetime module from timestamp() function, we can get esal: 10000
exact date and time. eaddr: HYD
e1 eno: 100
ename: Durga
Q) To Print all Statistics of File abc.txt esal: 10000
eaddr: HYD
1) import os
2) stats=os.stat("abc.txt")
3) print(stats) eno: 100 abc.txt
ename: Durga pickle load (f)
esal: 10000
Output eaddr: HYD unpickling
os.stat_result(st_mode=33206, st_ino=844424930132788, st_dev=2657980798, st_nlin e2
k=1, st_uid=0, st_gid=0, st_size=22410, st_atime=1505451446, st_mtime=1505538999
, st_ctime=1505451446) Writing and Reading State of Object by using pickle Module:
Q) To Print specified Properties 1) import pickle
2) class Employee:
1) import os 3) def __init__(self,eno,ename,esal,eaddr):
2) from datetime import * 4) self.eno=eno;
3) stats=os.stat("abc.txt") 5) self.ename=ename;
4) print("File Size in Bytes:",stats.st_size) 6) self.esal=esal;
5) print("File Last Accessed Time:",datetime.fromtimestamp(stats.st_atime)) 7) self.eaddr=eaddr;
6) print("File Last Modified Time:",datetime.fromtimestamp(stats.st_mtime)) 8) def display(self):
9) print(self.eno,"\t",self.ename,"\t",self.esal,"\t",self.eaddr)
10) with open("emp.dat","wb") as f:
11) e=Employee(100,"Durga",1000,"Hyd")
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
119  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
120  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
12) pickle.dump(e,f) 7) obj.display()
13) print("Pickling of Employee Object completed...") 8) except EOFError:
14) 9) print("All employees Completed")
15) with open("emp.dat","rb") as f: 10) break
16) obj=pickle.load(f) 11) f.close()
17) print("Printing Employee Information after unpickling")
18) obj.display()

Writing Multiple Employee Objects to the File:


emp.py:

1) class Employee:
2) def __init__(self,eno,ename,esal,eaddr):
3) self.eno=eno;
4) self.ename=ename;
5) self.esal=esal;
6) self.eaddr=eaddr;
7) def display(self):
8)
9) print(self.eno,"\t",self.ename,"\t",self.esal,"\t",self.eaddr)

pick.py:

1) import emp,pickle
2) f=open("emp.dat","wb")
3) n=int(input("Enter The number of Employees:"))
4) for i in range(n):
5) eno=int(input("Enter Employee Number:"))
6) ename=input("Enter Employee Name:")
7) esal=float(input("Enter Employee Salary:"))
8) eaddr=input("Enter Employee Address:")
9) e=emp.Employee(eno,ename,esal,eaddr)
10) pickle.dump(e,f)
11) print("Employee Objects pickled successfully")

unpick.py:

1) import emp,pickle
2) f=open("emp.dat","rb")
3) print("Employee Details:")
4) while True:
5) try:
6) obj=pickle.load(f)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
121  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
122  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Multi Tasking:
Executing several tasks simultaneously is the concept of multitasking.

There are 2 types of Multi Tasking


1) Process based Multi Tasking
2) Thread based Multi Tasking

1) Process based Multi Tasking:


Executing several tasks simmultaneously where each task is a seperate independent
process is called process based multi tasking.
Eg: while typing python program in the editor we can listen mp3 audio songs from the
same system. At the same time we can download a file from the internet. All these
taks are executing simultaneously and independent of each other. Hence it is process
based multi tasking.

MULTI
This type of multi tasking is best suitable at operating system level.

2) Thread based MultiTasking:


 Executing several tasks simultaneously where each task is a seperate independent part
of the same program, is called Thread based multi tasking, and each independent part
is called a Thread.
 This type of multi tasking is best suitable at programmatic level.

THREADING Note: Whether it is process based or thread based, the main advantage of multi tasking is
to improve performance of the system by reducing response time.

The main important application areas of multi threading are:


1) To implement Multimedia graphics
2) To develop animations
3) To develop video games
4) To develop web and application servers
etc...

Note: Where ever a group of independent jobs are available, then it is highly
recommended to execute simultaneously instead of executing one by one.For such type of
cases we should go for Multi Threading.
 Python provides one inbuilt module "threading" to provide support for developing
threads. Hence developing multi threaded Programs is very easy in python.
 Every Python Program by default contains one thread which is nothing but
MainThread.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
123  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
124  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Q) Program to print Name of Current executing Thread 1) from threading import *
2) class MyThread(Thread):
3) def run(self):
1) import threading
4) for i in range(10):
2) print("Current Executing Thread:",threading.current_thread().getName())
5) print("Child Thread-1")
6) t=MyThread()
Output: Current Executing Thread: MainThread 7) t.start()
8) for i in range(10):
Note: threading module contains function current_thread() which returns the current 9) print("Main Thread-1")
executing Thread object. On this object if we call getName() method then we will get
current executing thread name.
3) Creating a Thread without extending Thread Class
The ways of Creating Thread in Python: 1) from threading import *
We can create a thread in Python by using 3 ways 2) class Test:
1) Creating a Thread without using any class 3) def display(self):
2) Creating a Thread by extending Thread class 4) for i in range(10):
3) Creating a Thread without extending Thread class 5) print("Child Thread-2")
6) obj=Test()
1) Creating a Thread without using any Class 7) t=Thread(target=obj.display)
8) t.start()
1) from threading import * 9) for i in range(10):
2) def display(): 10) print("Main Thread-2")
3) for i in range(1,11):
4) print("Child Thread") Without Multi Threading
5) t=Thread(target=display) #creating Thread object
6) t.start() #starting of Thread 1) from threading import *
7) for i in range(1,11): 2) import time
8) print("Main Thread") 3) def doubles(numbers):
4) for n in numbers:
If multiple threads present in our program, then we cannot expect execution order and 5) time.sleep(1)
hence we cannot expect exact output for the multi threaded programs. B'z of this we 6) print("Double:",2*n)
cannot provide exact output for the above program.It is varied from machine to machine 7) def squares(numbers):
and run to run. 8) for n in numbers:
9) time.sleep(1)
Note: Thread is a pre defined class present in threading module which can be used to 10) print("Square:",n*n)
create our own Threads. 11) numbers=[1,2,3,4,5,6]
12) begintime=time.time()
13) doubles(numbers)
2) Creating a Thread by extending Thread Class 14) squares(numbers)
We have to create child class for Thread class. In that child class we have to override 15) print("The total time taken:",time.time()-begintime)
run() method with our required job. Whenever we call start() method then
automatically run() method will be executed and performs our job.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
125  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
126  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
With Multi Threading Thread Identification Number (ident):
For every thread internally a unique identification number is available. We can access this
1) from threading import * id by using implicit variable "ident"
2) import time
3) def doubles(numbers): 1) from threading import *
4) for n in numbers: 2) def test():
5) time.sleep(1) 3) print("Child Thread")
6) print("Double:",2*n) 4) t=Thread(target=test)
7) def squares(numbers): 5) t.start()
8) for n in numbers: 6) print("Main Thread Identification Number:",current_thread().ident)
9) time.sleep(1) 7) print("Child Thread Identification Number:",t.ident)
10) print("Square:",n*n)
11)
Output:
12) numbers=[1,2,3,4,5,6]
Child Thread
13) begintime=time.time()
Main Thread Identification Number: 2492
14) t1=Thread(target=doubles,args=(numbers,))
Child Thread Identification Number: 2768
15) t2=Thread(target=squares,args=(numbers,))
16) t1.start()
17) t2.start()
active_count():
18) t1.join() This function returns the number of active threads currently running.
19) t2.join()
1) from threading import *
20) print("The total time taken:",time.time()-begintime)
2) import time
3) def display():
Setting and Getting Name of a Thread: 4) print(current_thread().getName(),"...started")
Every thread in python has name. It may be default name generated by Python or 5) time.sleep(3)
Customized Name provided by programmer. 6) print(current_thread().getName(),"...ended")
7) print("The Number of active Threads:",active_count())
We can get and set name of thread by using the following Thread class methods. 8) t1=Thread(target=display,name="ChildThread1")
t.getName()  Returns Name of Thread 9) t2=Thread(target=display,name="ChildThread2")
t.setName(newName)  To set our own name 10) t3=Thread(target=display,name="ChildThread3")
11) t1.start()
Note: Every Thread has implicit variable "name" to represent name of Thread. 12) t2.start()
13) t3.start()
1) from threading import * 14) print("The Number of active Threads:",active_count())
2) print(current_thread().getName()) 15) time.sleep(5)
3) current_thread().setName("Pawan Kalyan") 16) print("The Number of active Threads:",active_count())
4) print(current_thread().getName())
5) print(current_thread().name) Output:
D:\python_classes>py test.py
Output The Number of active Threads: 1
MainThread ChildThread1 ...started
Pawan Kalyan ChildThread2 ...started
Pawan Kalyan ChildThread3 ...started
The Number of active Threads: 4

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
127  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
128  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
ChildThread1 ...ended isAlive() Method:
ChildThread2 ...ended
isAlive() method checks whether a thread is still executing or not.
ChildThread3 ...ended
The Number of active Threads: 1
1) from threading import *
2) import time
enumerate() Function: 3) def display():
This function returns a list of all active threads currently running. 4) print(current_thread().getName(),"...started")
5) time.sleep(3)
1) from threading import * 6) print(current_thread().getName(),"...ended")
2) import time 7) t1=Thread(target=display,name="ChildThread1")
3) def display(): 8) t2=Thread(target=display,name="ChildThread2")
4) print(current_thread().getName(),"...started") 9) t1.start()
5) time.sleep(3) 10) t2.start()
6) print(current_thread().getName(),"...ended") 11)
7) t1=Thread(target=display,name="ChildThread1") 12) print(t1.name,"is Alive :",t1.isAlive())
8) t2=Thread(target=display,name="ChildThread2") 13) print(t2.name,"is Alive :",t2.isAlive())
9) t3=Thread(target=display,name="ChildThread3") 14) time.sleep(5)
10) t1.start() 15) print(t1.name,"is Alive :",t1.isAlive())
11) t2.start() 16) print(t2.name,"is Alive :",t2.isAlive())
12) t3.start()
13) l=enumerate() Output:
14) for t in l: D:\python_classes>py test.py
15) print("Thread Name:",t.name) ChildThread1 ...started
16) time.sleep(5) ChildThread2 ...started
17) l=enumerate() ChildThread1 is Alive : True
18) for t in l: ChildThread2 is Alive : True
19) print("Thread Name:",t.name) ChildThread1 ...ended
ChildThread2 ...ended
Output: ChildThread1 is Alive : False
D:\python_classes>py test.py ChildThread2 is Alive : False
ChildThread1 ...started
ChildThread2 ...started join() Method:
ChildThread3 ...started If a thread wants to wait until completing some other thread then we should go for join()
Thread Name: MainThread method.
Thread Name: ChildThread1
Thread Name: ChildThread2 1) from threading import *
Thread Name: ChildThread3 2) import time
ChildThread1 ...ended 3) def display():
ChildThread2 ...ended 4) for i in range(10):
ChildThread3 ...ended 5) print("Seetha Thread")
Thread Name: MainThread 6) time.sleep(2)
7)
8) t=Thread(target=display)
9) t.start()

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
129  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
130  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
10) t.join()#This Line executed by Main Thread In this case Main Thread waited only 5 seconds.
11) for i in range(10):
12) print("Rama Thread") Output
Seetha Thread
In the above example Main Thread waited until completing child thread. In this case Seetha Thread
output is: Seetha Thread
Seetha Thread Rama Thread
Seetha Thread Rama Thread
Seetha Thread Rama Thread
Seetha Thread Rama Thread
Seetha Thread Rama Thread
Seetha Thread Rama Thread
Seetha Thread Rama Thread
Seetha Thread Rama Thread
Seetha Thread Rama Thread
Seetha Thread Rama Thread
Rama Thread Seetha Thread
Rama Thread Seetha Thread
Rama Thread Seetha Thread
Rama Thread Seetha Thread
Rama Thread Seetha Thread
Rama Thread Seetha Thread
Rama Thread Seetha Thread
Rama Thread
Rama Thread Summary of all methods related to threading module and Thread
Rama Thread

Note: We can call join() method with time period also. Daemon Threads:
 The threads which are running in the background are called Daemon Threads.
t.join(seconds)  The main objective of Daemon Threads is to provide support for Non Daemon
In this case thread will wait only specified amount of time. Threads( like main thread)
Eg: Garbage Collector
1) from threading import *  Whenever Main Thread runs with low memory, immediately PVM runs Garbage
2) import time Collector to destroy useless objects and to provide free memory,so that Main Thread
3) def display(): can continue its execution without having any memory problems.
4) for i in range(10):  We can check whether thread is Daemon or not by using t.isDaemon() method of
5) print("Seetha Thread") Thread class or by using daemon property.
6) time.sleep(2)
7) 1) from threading import *
8) t=Thread(target=display) 2) print(current_thread().isDaemon()) #False
9) t.start() 3) print(current_thread().daemon) #False
10) t.join(5)#This Line executed by Main Thread
11) for i in range(10):  We can change Daemon nature by using setDaemon() method of Thread class.
12) print("Rama Thread") t.setDaemon(True)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
131  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
132  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
 But we can use this method before starting of Thread.i.e once thread started,we In the above program if we comment Line-1 then both Main Thread and Child Threads are
cannot change its Daemon nature,otherwise we will get Non Daemon and hence both will be executed until their completion.
 RuntimeException:cannot set daemon status of active thread. In this case output is:

1) from threading import * Lazy Thread


2) print(current_thread().isDaemon()) Lazy Thread
3) current_thread().setDaemon(True) Lazy Thread
End Of Main Thread
RuntimeError: cannot set daemon status of active thread Lazy Thread
Lazy Thread
Lazy Thread
Default Nature: Lazy Thread
By default Main Thread is always non-daemon.But for the remaining threads Daemon
Lazy Thread
nature will be inherited from parent to child.i.e if the Parent Thread is Daemon then child
Lazy Thread
thread is also Daemon and if the Parent Thread is Non Daemon then ChildThread is also
Lazy Thread
Non Daemon.
If we are not commenting Line-1 then Main Thread is Non-Daemon and Child Thread is
1) from threading import *
Daemon. Hence whenever MainThread terminates automatically child thread will be
2) def job():
terminated. In this case output is
3) print("Child Thread")
4) t=Thread(target=job)
Lazy Thread
5) print(t.isDaemon())#False
Lazy Thread
6) t.setDaemon(True)
Lazy Thread
7) print(t.isDaemon()) #True
End of Main Thread
Note: Main Thread is always Non-Daemon and we cannot change its Daemon Nature b'z
it is already started at the beginning only. Synchronization:
If multiple threads are executing simultaneously then there may be a chance of data
Whenever the last Non-Daemon Thread terminates automatically all Daemon Threads will inconsistency problems.
be terminated.
1) from threading import *
1) from threading import * 2) import time
2) import time 3) def wish(name):
3) def job(): 4) for i in range(10):
4) for i in range(10): 5) print("Good Evening:",end='')
5) print("Lazy Thread") 6) time.sleep(2)
6) time.sleep(2) 7) print(name)
7) 8) t1=Thread(target=wish,args=("Dhoni",))
8) t=Thread(target=job) 9) t2=Thread(target=wish,args=("Yuvraj",))
9) #t.setDaemon(True)===>Line-1 10) t1.start()
10) t.start() 11) t2.start()
11) time.sleep(5)
12) print("End Of Main Thread") Output
Good Evening:Good Evening:Yuvraj
Dhoni

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
133  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
134  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Good Evening:Good Evening:Yuvraj 3) l=Lock()
Dhoni 4) def wish(name):
.... 5) l.acquire()
6) for i in range(10):
 We are getting irregular output b'z both threads are executing simultaneously wish() 7) print("Good Evening:",end='')
function. 8) time.sleep(2)
 To overcome this problem we should go for synchronization. 9) print(name)
 In synchronization the threads will be executed one by one so that we can overcome 10) l.release()
data inconsistency problems. 11)
 Synchronization means at a time only one Thread 12) t1=Thread(target=wish,args=("Dhoni",))
13) t2=Thread(target=wish,args=("Yuvraj",))
The main application areas of synchronization are 14) t3=Thread(target=wish,args=("Kohli",))
1) Online Reservation system 15) t1.start()
2) Funds Transfer from joint accounts 16) t2.start()
etc 17) t3.start()

In Python, we can implement synchronization by using the following In the above program at a time only one thread is allowed to execute wish() method and
1) Lock hence we will get regular output.
2) RLock
3) Semaphore Problem with Simple Lock:
The standard Lock object does not care which thread is currently holding that lock.If the
Synchronization By using Lock Concept: lock is held and any thread attempts to acquire lock, then it will be blocked,even the same
 Locks are the most fundamental synchronization mechanism provided by threading thread is already holding that lock.
module.
 We can create Lock object as follows l = Lock() 1) from threading import *
 The Lock object can be hold by only one thread at a time.If any other thread required 2) l=Lock()
the same lock then it will wait until thread releases lock. (Similar to common wash 3) print("Main Thread trying to acquire Lock")
rooms, public telephone booth etc) 4) l.acquire()
5) print("Main Thread trying to acquire Lock Again")
 A Thread can acquire the lock by using acquire() Method l.acquire()
6) l.acquire()
 A Thread can release the lock by using release() Method l.release()
Output
Note: To call release() method compulsory thread should be owner of that lock.i.e thread
D:\python_classes>py test.py
should has the lock already,otherwise we will get Runtime Exception saying
Main Thread trying to acquire Lock
RuntimeError: release unlocked lock.
Main Thread trying to acquire Lock Again
--
1) from threading import *
In the above Program main thread will be blocked b'z it is trying to acquire the lock second
2) l=Lock()
time.
3) #l.acquire()  1
4) l.release()
Note: To kill the blocking thread from windows command prompt we have to use
If we are commenting line-1 then we will get RuntimeError: release unlocked lock ctrl+break. Here ctrl+C won't work.

1) from threading import * If the Thread calls recursive functions or nested access to resources,then the thread may
2) import time trying to acquire the same lock again and again,which may block our thread.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
135  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
136  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Hence Traditional Locking mechanism won't work for executing recursive functions. 8) else:
9) result=n*factorial(n-1)
To overcome this problem, we should go for RLock(Reentrant Lock). Reentrant means the 10) l.release()
thread can acquire the same lock again and again.If the lock is held by other threads then 11) return result
only the thread will be blocked. 12)
13) def results(n):
Reentrant facility is available only for owner thread but not for other threads. 14) print("The Factorial of",n,"is:",factorial(n))
15)
1) from threading import * 16) t1=Thread(target=results,args=(5,))
2) l=RLock() 17) t2=Thread(target=results,args=(9,))
3) print("Main Thread trying to acquire Lock") 18) t1.start()
4) l.acquire() 19) t2.start()
5) print("Main Thread trying to acquire Lock Again")
6) l.acquire() Output:
The Factorial of 5 is: 120
In this case Main Thread won't be Locked b'z thread can acquire the lock any number of The Factorial of 9 is: 362880
times.
In the above program instead of RLock if we use normal Lock then the thread will be
This RLock keeps track of recursion level and hence for every acquire() call compulsory blocked.
release() call should be available. i.e the number of acquire() calls and release() calls
should be matched then only lock will be released.
Difference between Lock and RLock
Eg: Lock RLock
l=RLock()
1) Lock object can be acquired by only one 1) RLock object can be acquired by only one
l.acquire()
thread at a time.Even owner thread also thread at a time, but owner thread can
l.acquire()
cannot acquire multiple times. acquire same lock object multiple times.
l.release()
l.release() 2) Not suitable to execute recursive 2) Best suitable to execute recursive
functions and nested access calls. functions and nested access calls.
After 2 release() calls only the Lock will be released. 3) In this case Lock object will takes care 3) In this case RLock object will takes care
only Locked or unlocked and it never takes whether Locked or unlocked and owner
Note: care about owner thread and recursion thread information, recursiion level.
1) Only owner thread can acquire the lock multiple times level.
2) The number of acquire() calls and release() calls should be matched.
Synchronization by using Semaphore:
Demo Program for Synchronization by using RLock: ☕ In the case of Lock and RLock, at a time only one thread is allowed to execute.
☕ Sometimes our requirement is at a time a particular number of threads are allowed to
1) from threading import * access(like at a time 10 memebers are allowed to access database server,4 members
2) import time are allowed to access Network connection etc).To handle this requirement we cannot
3) l=RLock() use Lock and RLock concepts and we should go for Semaphore concept.
4) def factorial(n):
☕ Semaphore can be used to limit the access to the shared resources with limited
5) l.acquire()
capacity.
6) if n==0:
☕ Semaphore is advanced Synchronization Mechanism.
7) result=1

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
137  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
138  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
☕ We can create Semaphore object as follows s = Semaphore(counter)
☕ Here counter represents the maximum number of threads are allowed to access
Bounded Semaphore:
Normal Semaphore is an unlimited semaphore which allows us to call release() method
simultaneously. The default value of counter is 1.
any number of times to increment counter.The number of release() calls can exceed the
☕ Whenever thread executes acquire() method,then the counter value will be
number of acquire() calls also.
decremented by 1 and if thread executes release() method then the counter value will
be incremented by 1. 1) from threading import *
☕ i.e for every acquire() call counter value will be decremented and for every release() 2) s=Semaphore(2)
call counter value will be incremented. 3) s.acquire()
4) s.acquire()
Case-1: s = Semaphore() 5) s.release()
In this case counter value is 1 and at a time only one thread is allowed to access. It is 6) s.release()
exactly same as Lock concept. 7) s.release()
8) s.release()
Case-2: s = Semaphore(3) 9) print("End")
In this case Semaphore object can be accessed by 3 threads at a time.The remaining
threads have to wait until releasing the semaphore. ☕ It is valid because in normal semaphore we can call release() any number of times.
☕ BounedSemaphore is exactly same as Semaphore except that the number of release()
1) from threading import * calls should not exceed the number of acquire() calls,otherwise we will get
2) import time ValueError: Semaphore released too many times
3) s=Semaphore(2)
4) def wish(name): 1) from threading import *
5) s.acquire() 2) s=BoundedSemaphore(2)
6) for i in range(10): 3) s.acquire()
7) print("Good Evening:",end='') 4) s.acquire()
8) time.sleep(2) 5) s.release()
9) print(name) 6) s.release()
10) s.release() 7) s.release()
11) 8) s.release()
12) t1=Thread(target=wish,args=("Dhoni",)) 9) print("End")
13) t2=Thread(target=wish,args=("Yuvraj",))
14) t3=Thread(target=wish,args=("Kohli",)) ValueError: Semaphore released too many times
15) t4=Thread(target=wish,args=("Rohit",)) It is invalid b'z the number of release() calls should not exceed the number of acquire()
16) t5=Thread(target=wish,args=("Pandya",)) calls in BoundedSemaphore.
17) t1.start()
18) t2.start() Note: To prevent simple programming mistakes, it is recommended to use
19) t3.start() BoundedSemaphore over normal Semaphore.
20) t4.start()
21) t5.start()
Difference between Lock and Semaphore:
In the above program at a time 2 threads are allowed to access semaphore and hence 2 At a time Lock object can be acquired by only one thread, but Semaphore object can be
threads are allowed to execute wish() function. acquired by fixed number of threads specified by counter value.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
139  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
140  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Conclusion: Demo Program-1:
The main advantage of synchronization is we can overcome data inconsistency
problems.But the main disadvantage of synchronization is it increases waiting time of 1) from threading import *
threads and creates performance problems. Hence if there is no specific requirement then 2) import time
it is not recommended to use synchronization. 3) def producer():
4) time.sleep(5)
5) print("Producer thread producing items:")
6) print("Producer thread giving notification by setting event")
Inter Thread Communication: 7) event.set()
☕ Some times as the part of programming requirement, threads are required to 8) def consumer():
communicate with each other. This concept is nothing but interthread communication. 9) print("Consumer thread is waiting for updation")
☕ Eg: After producing items Producer thread has to communicate with Consumer thread 10) event.wait()
to notify about new item.Then consumer thread can consume that new item. 11) print("Consumer thread got notification and consuming items")
☕ In Python, we can implement interthread communication by using the following ways 12)
1) Event 13) event=Event()
2) Condition 14) t1=Thread(target=producer)
3) Queue 15) t2=Thread(target=consumer)
etc 16) t1.start()
17) t2.start()
Inter Thread Communication by using Event Objects: Output:
☕ Event object is the simplest communication mechanism between the threads. One Consumer thread is waiting for updation
thread signals an event and other thereds wait for it. Producer thread producing items
☕ We can create Event object as follows... Producer thread giving notification by setting event
☕ event = threading.Event() Consumer thread got notification and consuming items
☕ Event manages an internal flag that can set() or clear()
☕ Threads can wait until event set. Demo Program-2:

1) from threading import *


Methods of Event Class: 2) import time
1) set()  internal flag value will become True and it represents GREEN signal for all 3) def trafficpolice():
waiting threads. 4) while True:
2) clear()  inernal flag value will become False and it represents RED signal for all 5) time.sleep(10)
waiting threads. 6) print("Traffic Police Giving GREEN Signal")
3) isSet()  This method can be used whether the event is set or not 7) event.set()
4) wait()|wait(seconds)  Thread can wait until event is set 8) time.sleep(20)
9) print("Traffic Police Giving RED Signal")
Pseudo Code: 10) event.clear()
event = threading.Event() 11) def driver():
#consumer thread has to wait until event is set 12) num=0
event.wait() 13) while True:
#producer thread can set or clear event 14) print("Drivers waiting for GREEN Signal")
event.set() 15) event.wait()
event.clear() 16) print("Traffic Signal is GREEN...Vehicles can move")
17) while event.isSet():
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
141  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
142  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
18) num=num+1
19) print("Vehicle No:",num,"Crossing the Signal")
Case Study:
20) time.sleep(2) The producing thread needs to acquire the Condition before producing item to the
21) print("Traffic Signal is RED...Drivers have to wait") resource and notifying the consumers.
22) event=Event()
23) t1=Thread(target=trafficpolice) #Producer Thread
24) t2=Thread(target=driver) ...generate item..
25) t1.start() condition.acquire()
26) t2.start() ...add item to the resource...
condition.notify()#signal that a new item is available(notifyAll())
In the above program driver thread has to wait until Trafficpolice thread sets event.ie until condition.release()
giving GREEN signal.Once Traffic police thread sets event(giving GREEN signal),vehicles can
cross the signal. Once traffic police thread clears event (giving RED Signal)then the driver The Consumer must acquire the Condition and then it can consume items from the
thread has to wait. resource

#Consumer Thread
Inter Thread Communication by using Condition Object: condition.acquire()
☕ Condition is the more advanced version of Event object for interthread condition.wait()
communication.A condition represents some kind of state change in the application consume item
like producing item or consuming item. Threads can wait for that condition and condition.release()
threads can be notified once condition happend.i.e Condition object allows one or
more threads to wait until notified by another thread. Demo Program-1:
☕ Condition is always associated with a lock (ReentrantLock).
☕ A condition has acquire() and release() methods that call the corresponding methods 1) from threading import *
of the associated lock. 2) def consume(c):
☕ We can create Condition object as follows condition = threading.Condition() 3) c.acquire()
4) print("Consumer waiting for updation")
5) c.wait()
Methods of Condition: 6) print("Consumer got notification & consuming the item")
7) c.release()
1) acquire()  To acquire Condition object before producing or consuming items.i.e 8)
thread acquiring internal lock. 9) def produce(c):
10) c.acquire()
2) release()  To release Condition object after producing or consuming items. i.e thread 11) print("Producer Producing Items")
releases internal lock 12) print("Producer giving Notification")
13) c.notify()
3) wait()|wait(time)  To wait until getting Notification or time expired 14) c.release()
15)
4) notify()  To give notification for one waiting thread 16) c=Condition()
17) t1=Thread(target=consume,args=(c,))
5) notifyAll()  To give notification for all waiting threads 18) t2=Thread(target=produce,args=(c,))
19) t1.start()
20) t2.start()

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
143  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
144  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Output In the above program Consumer thread expecting updation and hence it is responsible to
Consumer waiting for updation call wait() method on Condition object.
Producer Producing Items Producer thread performing updation and hence it is responsible to call notify() or
Producer giving Notification notifyAll() on Condition object.
Consumer got notification & consuming the item
Inter Tread Communication by using Queue:
Demo Program-2: ☕ Queues Concept is the most enhanced Mechanism for interthread communication and
to share data between threads.
1) from threading import *
☕ Queue internally has Condition and that Condition has Lock.Hence whenever we are
2) import time
using Queue we are not required to worry about Synchronization.
3) import random
4) items=[] ☕ If we want to use Queues first we should import queue module import queue
5) def produce(c): ☕ We can create Queue object as follows q = queue.Queue()
6) while True:
7) c.acquire() Important Methods of Queue:
8) item=random.randint(1,100) 1) put(): Put an item into the queue.
9) print("Producer Producing Item:",item) 2) get(): Remove and return an item from the queue.
10) items.append(item)
11) print("Producer giving Notification") Producer Thread uses put() method to insert data in the queue. Internally this method has
12) c.notify() logic to acquire the lock before inserting data into queue. After inserting data lock will be
13) c.release() released automatically.
14) time.sleep(5)
15) put() method also checks whether the queue is full or not and if queue is full then the
16) def consume(c): Producer thread will entered in to waiting state by calling wait() method internally.
17) while True:
18) c.acquire() Consumer Thread uses get() method to remove and get data from the queue. Internally
19) print("Consumer waiting for updation") this method has logic to acquire the lock before removing data from the queue.Once
20) c.wait() removal completed then the lock will be released automatically.
21) print("Consumer consumed the item",items.pop())
22) c.release() If the queue is empty then consumer thread will entered into waiting state by calling
23) time.sleep(5) wait() method internally.Once queue updated with data then the thread will be notified
24) automatically.
25) c=Condition()
26) t1=Thread(target=consume,args=(c,)) Note: The Queue Module takes care of locking for us which is a great Advantage.
27) t2=Thread(target=produce,args=(c,))
28) t1.start() 1) from threading import *
29) t2.start() 2) import time
3) import random
Output 4) import queue
Consumer waiting for updation 5) def produce(q):
Producer Producing Item: 49 6) while True:
Producer giving Notification 7) item=random.randint(1,100)
Consumer consumed the item 49 8) print("Producer Producing Item:",item)
..... 9) q.put(item)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
145  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
146  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
10) print("Producer giving Notification") 2) LIFO Queue:
11) time.sleep(5)
The removal will be happend in the reverse order of Insertion (Last In First Out)
12) def consume(q):
13) while True:
1) import queue
14) print("Consumer waiting for updation")
2) q=queue.LifoQueue()
15) print("Consumer consumed the item:",q.get())
3) q.put(10)
16) time.sleep(5)
4) q.put(5)
17)
5) q.put(20)
18) q=queue.Queue()
6) q.put(15)
19) t1=Thread(target=consume,args=(q,))
7) while not q.empty():
20) t2=Thread(target=produce,args=(q,))
8) print(q.get(),end=' ')
21) t1.start()
22) t2.start()
Output: 15 20 5 10
Output
Consumer waiting for updation 3) Priority Queue:
Producer Producing Item: 58 The elements will be inserted based on some priority order.
Producer giving Notification
Consumer consumed the item: 58 1) import queue
2) q=queue.PriorityQueue()
3) q.put(10)
Types of Queues: 4) q.put(5)
Python Supports 3 Types of Queues. 5) q.put(20)
6) q.put(15)
1) FIFO Queue: 7) while not q.empty():
8) print(q.get(),end=' ')
q = queue.Queue()
This is Default Behaviour. In which order we put items in the queue, in the same order
the items will come out (FIFO-First In First Out). Output: 5 10 15 20

1) import queue Eg 2: If the data is non-numeric, then we have to provide our data in the form of tuple.
2) q=queue.Queue() (x,y)
3) q.put(10) x is priority
4) q.put(5) y is our element
5) q.put(20)
6) q.put(15) 1) import queue
7) while not q.empty(): 2) q=queue.PriorityQueue()
8) print(q.get(),end=' ') 3) q.put((1,"AAA"))
4) q.put((3,"CCC"))
Output: 10 5 20 15 5) q.put((2,"BBB"))
6) q.put((4,"DDD"))
7) while not q.empty():
8) print(q.get()[1],end=' ')

Output: AAA BBB CCC DDD

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
147  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
148  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Good Programming Practices with usage of Locks: Example for File:
with open('demo.txt','w') as f:
f.write("Hello...")
Case-1:
It is highly recommended to write code of releasing locks inside finally block.The
Example for Lock:
advantage is lock will be released always whether exception raised or not raised and
lock = threading.Lock()
whether handled or not handled.
with lock:
perform required safe operations
l = threading.Lock()
lock will be released automatically
l.acquire()
try:
perform required safe operations Demo Program:
finally:
l.release() 1) from threading import *
2) import time
3) lock=Lock()
Demo Program: 4) def wish(name):
5) with lock:
1) from threading import *
6) for i in range(10):
2) import time
7) print("Good Evening:",end='')
3) l=Lock()
8) time.sleep(2)
4) def wish(name):
9) print(name)
5) l.acquire()
10) t1=Thread(target=wish,args=("Dhoni",))
6) try:
11) t2=Thread(target=wish,args=("Yuvraj",))
7) for i in range(10):
12) t3=Thread(target=wish,args=("Kohli",))
8) print("Good Evening:",end='')
13) t1.start()
9) time.sleep(2)
14) t2.start()
10) print(name) 15) t3.start()
11) finally:
12) l.release()
Q) What is the Advantage of using with Statement to acquire a Lock in
13)
14) t1=Thread(target=wish,args=("Dhoni",)) Threading?
15) t2=Thread(target=wish,args=("Yuvraj",)) Lock will be released automatically once control reaches end of with block and we are not
16) t3=Thread(target=wish,args=("Kohli",)) required to release explicitly.
17) t1.start()
18) t2.start() Note: We can use with statement in multithreading for the following cases:
19) t3.start()
1) Lock
2) RLock
Case-2: 3) Semaphore
 It is highly recommended to acquire lock by using with statement. The main advantage 4) Condition
of with statement is the lock will be released automatically once control reaches end
of with block and we are not required to release explicitly.
 This is exactly same as usage of with statement for files.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
149  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
150  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Storage Areas
As the Part of our Applications, we required to store our Data like Customers Information,
Billing Information, Calls Information etc.

To store this Data, we required Storage Areas. There are 2 types of Storage Areas.

1) Temporary Storage Areas


2) Permanent Storage Areas

1) Temporary Storage Areas:


 These are the Memory Areas where Data will be stored temporarily.
Eg: Python objects like List, Tuple, Dictionary.

PYTHON
 Once Python program completes its execution then these objects will be destroyed
automatically and data will be lost.

2) Permanent Storage Areas:


 Also known as Persistent Storage Areas. Here we can store Data permanently.
Eg: File Systems, Databases, Data warehouses, Big Data Technologies etc

File Systems:

DATABASE
File Systems can be provided by Local operating System. File Systems are best suitable to
store very less Amount of Information.

Limitations:
1) We cannot store huge Amount of Information.

PROGRAMMING
2) There is no Query Language support and hence operations will become very complex.
3) There is no Security for Data.
4) There is no Mechanism to prevent duplicate Data. Hence there may be a chance of Data
Inconsistency Problems.

To overcome the above Problems of File Systems, we should go for Databases.

Databases:
1) We can store Huge Amount of Information in the Databases.
2) Query Language Support is available for every Database and hence we can perform
Database Operations very easily.
3) To access Data present in the Database, compulsory username and pwd must be
required. Hence Data is secured.
4) Inside Database Data will be stored in the form of Tables. While developing Database
Table Schemas, Database Admin follow various Normalization Techniques and can
implement various Constraints like Unique Key Constrains, Primary Key Constraints etc
which prevent Data Duplication. Hence there is no chance of Data Inconsistency Problems.
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
151  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
152  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) Commit OR Rollback changes based on our requirement in the case of DML Queries
Limitations of Databases: (insert|update|delete)
1) Database cannot hold very Huge Amount of Information like Terabytes of Data.
2) Database can provide support only for Structured Data (Tabular Data OR Relational commit()  Saves the changes to the database
Data) and cannot provide support for Semi Structured Data (like XML Files) and rollback()  rolls all temporary changes back
Unstructured Data (like Video Files, Audio Files, Images etc)
6) Fetch the result from the Cursor object in the case of select queries
To overcome these Problems we should go for more Advanced Storage Areas like Big Data fetchone()  To fetch only one row
Technologies, Data warehouses etc. fetchall()  To fetch all rows and it returns a list of rows
fecthmany(n)  To fetch first n rows
Python Database Programming:
 Sometimes as the part of Programming requirement we have to connect to the Eg 1: data = cursor.fetchone()
database and we have to perform several operations like creating tables, inserting print(data)
data, updating data, deleting data, selecting data etc.
 We can use SQL Language to talk to the database and we can use Python to send those Eg 2: data = cursor.fetchall()
SQL commands to the database. for row in data:
 Python provides inbuilt support for several databases like Oracle, MySql, SqlServer, print(row)
GadFly, sqlite, etc.
 Python has seperate module for each database. 7) Close the Resources
Eg: cx_Oralce module for communicating with Oracle database After completing our operations it is highly recommended to close the resources in the
pymssql module for communicating with Microsoft Sql Server reverse order of their opening by using close() methods.
cursor.close()
con.close()
Standard Steps for Python database Programming:
1) Import database specific module Note: The following is the list of all important methods which can be used for python
Eg: import cx_Oracle database programming.

2) Establish Connection between Python Program and database. ⚽ connect()


We can create this Connection object by using connect() function of the module. ⚽ cursor()
con = cx_Oracle.connect(datbase information) ⚽ execute()
Eg: con = cx_Oracle.connect('scott/tiger@localhost') ⚽ executescript()
⚽ executemany()
3) To execute our sql queries and to hold results some special object is required, which is
⚽ commit()
nothing but Cursor object. We can create Cursor object by using cursor() method.
⚽ rollback()
cursor = con.cursor()
⚽ fetchone()
4) Execute SQL Queries By using Cursor object. For this we can use the following methods ⚽ fetchall()
⚽ execute(sqlquery)  To execute a Single SQL Query ⚽ fetchmany(n)
⚽ executescript(sqlqueries)  To execute a String of SQL Queries seperated by semi- ⚽ fetch
colon ';' ⚽ close()
⚽ executemany()  To execute a Parameterized Query.
Eg: cursor.execute("select * from employees") These methods won't be changed from database to database and same for all databases.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
153  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
154  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
_signal difflib pip unicodedata
Working with Oracle Database: _sitebuiltins dis pipes unittest
From Python Program if we want to communicate with any database, some translator _socket distutils pkg_resources unpick
must be required to translate Python calls into Database specific calls and Database _sqlite3 doctest pkgutil update
specific calls into Python calls.This translator is nothing but Driver/Connector. _sre dummy_threading platform urllib
_ssl durgamath plistlib uu
Diagram _stat easy_install polymorph uuid
.....
For Oracle database the name of driver needed is cx_Oracle.
cx_Oracle is a Python extension module that enables access to Oracle Database.It can be
used for both Python2 and Python3. It can work with any version of Oracle database like App 1) Program to Connect with Oracle Database and print
9,10,11 and 12. its Version
Installing cx_Oracle: 1) import cx_Oracle
From Normal Command Prompt (But not from Python console) execute the following 2) con=cx_Oracle.connect('scott/tiger@localhost')
command 3) print(con.version)
4) con.close()
D:\python_classes>pip install cx_Oracle
Output
Collecting cx_Oracle D:\python_classes>py db1.py
Downloading cx_Oracle-6.0.2-cp36-cp36m-win32.whl (100kB) 11.2.0.2.0
100% |-----------| 102kB 256kB/s
Installing collected packages: cx-Oracle App 2) Write a Program to Create Employees Table in the
Successfully installed cx-Oracle-6.0.2
Oracle Database
employees(eno,ename,esal,eaddr)
How to Test Installation:
From python console execute the following command: 1) import cx_Oracle
>>> help("modules") 2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
In the output we can see cx_Oracle 4) cursor=con.cursor()
.... 5) cursor.execute("create table employees(eno number,ename varchar2(10),esal n
_multiprocessing crypt ntpath timeit umber(10,2),eaddr varchar2(10))")
_opcode csv nturl2path tkinter 6) print("Table created successfully")
_operator csvr numbers token 7) except cx_Oracle.DatabaseError as e:
_osx_support csvw opcode tokenize 8) if con:
_overlapped ctypes operator trace 9) con.rollback()
_pickle curses optparse traceback 10) print("There is a problem with sql",e)
_pydecimal custexcept os tracemalloc 11) finally:
_pyio cx_Oracle parser try 12) if cursor:
_random data pathlib tty 13) cursor.close()
_sha1 datetime pdb turtle 14) if con:
_sha256 dbm pick turtledemo 15) con.close()
_sha3 decimal pickle types
_sha512 demo pickletools typing

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
155  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
156  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
App 3) Write a Program to Drop Employees Table from App 4) Write a Program to Insert Multiple Rows in the
Oracle Database? Employees Table by using executemany() Method
1) import cx_Oracle 1) import cx_Oracle
2) try: 2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost') 3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor() 4) cursor=con.cursor()
5) cursor.execute("drop table employees") 5) sql="insert into employees values(:eno,:ename,:esal,:eaddr)"
6) print("Table dropped successfully") 6) records=[(200,'Sunny',2000,'Mumbai'),
7) except cx_Oracle.DatabaseError as e: 7) (300,'Chinny',3000,'Hyd'),
8) if con: 8) (400,'Bunny',4000,'Hyd')]
9) con.rollback() 9) cursor.executemany(sql,records)
10) print("There is a problem with sql",e) 10) con.commit()
11) finally: 11) print("Records Inserted Successfully")
12) if cursor: 12) except cx_Oracle.DatabaseError as e:
13) cursor.close() 13) if con:
14) if con: 14) con.rollback()
15) con.close() 15) print("There is a problem with sql",e)
16) finally:
App 3) Write a Program to Insert a Single Row in the 17) if cursor:
18) cursor.close()
Employees Table 19) if con:
20) con.close()
1) import cx_Oracle
2) try: App 5) Write a Program to Insert Multiple Rows in the Employees
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor() Table with Dynamic Input from the Keyboard?
5) cursor.execute("insert into employees values(100,'Durga',1000,'Hyd')")
6) con.commit() 1) import cx_Oracle
7) print("Record Inserted Successfully") 2) try:
8) except cx_Oracle.DatabaseError as e: 3) con=cx_Oracle.connect('scott/tiger@localhost')
9) if con: 4) cursor=con.cursor()
10) con.rollback() 5) while True:
11) print("There is a problem with sql",e) 6) eno=int(input("Enter Employee Number:"))
12) finally: 7) ename=input("Enter Employee Name:")
13) if cursor: 8) esal=float(input("Enter Employee Salary:"))
14) cursor.close() 9) eaddr=input("Enter Employee Address:")
15) if con: 10) sql="insert into employees values(%d,'%s',%f,'%s')"
16) con.close() 11) cursor.execute(sql %(eno,ename,esal,eaddr))
12) print("Record Inserted Successfully")
Note: While performing DML Operations (insert|update|delte), compulsory we have to 13) option=input("Do you want to insert one more record[Yes|No] :")
use commit() method,then only the results will be reflected in the database. 14) if option=="No":
15) con.commit()
16) break

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
157  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
158  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
17) except cx_Oracle.DatabaseError as e: 6) sql="delete from employees where esal>%f"
18) if con: 7) cursor.execute(sql %(cutoffsalary))
19) con.rollback() 8) print("Records Deleted Successfully")
20) print("There is a problem with sql :",e) 9) con.commit()
21) finally: 10) except cx_Oracle.DatabaseError as e:
22) if cursor: 11) if con:
23) cursor.close() 12) con.rollback()
24) if con: 13) print("There is a problem with sql :",e)
25) con.close() 14) finally:
15) if cursor:
App 6) Write a Program to Update Employee Salaries with 16) cursor.close()
17) if con:
Increment for the certain Range with Dynamic Input 18) con.close()
Eg: Increment all employee salaries by 500 whose salary < 5000
App 8) Write a Program to Select all Employees info by
1) import cx_Oracle
2) try: using fetchone() Method?
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor() 1) import cx_Oracle
5) increment=float(input("Enter Increment Salary:")) 2) try:
6) salrange=float(input("Enter Salary Range:")) 3) con=cx_Oracle.connect('scott/tiger@localhost')
7) sql="update employees set esal=esal+%f where esal<%f" 4) cursor=con.cursor()
8) cursor.execute(sql %(increment,salrange)) 5) cursor.execute("select * from employees")
9) print("Records Updated Successfully") 6) row=cursor.fetchone()
10) con.commit() 7) while row is not None:
11) except cx_Oracle.DatabaseError as e: 8) print(row)
12) if con: 9) row=cursor.fetchone()
13) con.rollback() 10) except cx_Oracle.DatabaseError as e:
14) print("There is a problem with sql :",e) 11) if con:
15) finally: 12) con.rollback()
16) if cursor: 13) print("There is a problem with sql :",e)
17) cursor.close() 14) finally:
18) if con: 15) if cursor:
19) con.close() 16) cursor.close()
17) if con:
18) con.close()
App 7) Write a Program to Delete Employees whose Salary
Greater provided Salary as Dynamic Input? App 9) Write a Program to select all Employees info by using
Eg: delete all employees whose salary > 5000
fetchall() Method?
1) import cx_Oracle
2) try: 1) import cx_Oracle
3) con=cx_Oracle.connect('scott/tiger@localhost') 2) try:
4) cursor=con.cursor() 3) con=cx_Oracle.connect('scott/tiger@localhost')
5) cutoffsalary=float(input("Enter CutOff Salary:")) 4) cursor=con.cursor()

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
159  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
160  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
5) cursor.execute("select * from employees") Output
6) data=cursor.fetchall() D:\python_classes>py test.py
7) for row in data: Enter the number of required rows:3
8) print("Employee Number:",row[0]) (100, 'Durga', 1500.0, 'Hyd')
9) print("Employee Name:",row[1]) (200, 'Sunny', 2500.0, 'Mumbai')
10) print("Employee Salary:",row[2]) (300, 'Chinny', 3500.0, 'Hyd')
11) print("Employee Address:",row[3])
12) print() D:\python_classes>py test.py
13) print() Enter the number of required rows:4
14) except cx_Oracle.DatabaseError as e: (100, 'Durga', 1500.0, 'Hyd')
15) if con: (200, 'Sunny', 2500.0, 'Mumbai')
16) con.rollback() (300, 'Chinny', 3500.0, 'Hyd')
17) print("There is a problem with sql :",e) (400, 'Bunny', 4500.0, 'Hyd')
18) finally:
19) if cursor:
20) cursor.close() Working with MySQL Database:
21) if con: Current version: 5.7.19
22) con.close() Vendor: SUN Micro Systems/Oracle Corporation
Open Source and Freeware
App 10) Write a Program to select Employees info by using fetchmany() Default Port: 3306
Default user: root
Method and the required Number of Rows will be provided as
Dynamic Input? Note: In MySQL, everything we have to work with our own databases, which are also
known as Logical Databases.
1) import cx_Oracle
2) try:
The following are 4 Default Databases available in MySQL.
3) con=cx_Oracle.connect('scott/tiger@localhost')
 information_schema
4) cursor=con.cursor()
 mysql
5) cursor.execute("select * from employees")
 performance_schema
6) n=int(input("Enter the number of required rows:"))
 test
7) data=cursor.fetchmany(n)
8) for row in data:
In the above diagram only one physical database is available and 4 logical databases are
9) print(row)
available.
10) except cx_Oracle.DatabaseError as e:
11) if con:
12) con.rollback() Commonly used Commands in MySQL:
13) print("There is a problem with sql :",e)
14) finally: 1) To Know Available Databases
15) if cursor: mysql> show databases;
16) cursor.close()
17) if con: 2) To Create Our Own Logical Database
18) con.close() mysql> create database durgadb;

3) To Drop Our Own Database


mysql> drop database durgadb;

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
161  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
162  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
4) To Use a Particular Logical Database 6) print("Table Created...")
mysql> use durgadb; OR mysql> connect durgadb; 7)
8) sql = "insert into employees(eno, ename, esal, eaddr) VALUES(%s, %s, %s, %s)"
5) To Create a Table 9) records=[(100,'Sachin',1000,'Mumbai'),
create table employees(eno int(5) primary key,ename varchar(10),esal double(10,2), 10) (200,'Dhoni',2000,'Ranchi'),
eaddr varchar(10)); 11) (300,'Kohli',3000,'Delhi')]
12) cursor.executemany(sql,records)
6) To Insert Data 13) con.commit()
insert into employees values(100,'Durga',1000,'Hyd'); 14) print("Records Inserted Successfully...")
insert into employees values(200,'Ravi',2000,'Mumbai'); 15) cursor.execute("select * from employees")
16) data=cursor.fetchall()
In MySQL instead of single quotes we can use double quotes also. 17) for row in data:
18) print("Employee Number:",row[0])
19) print("Employee Name:",row[1])
20) print("Employee Salary:",row[2])
Driver/Connector Information: 21) print("Employee Address:",row[3])
From Python program if we want to communicates with MySql database, compulsory 22) print()
some translator is required to convert python specific calls into mysql database specific 23) print()
calls and mysql database specific calls into python specific calls. This translator is nothing 24) except mysql.connector.DatabaseError as e:
but Driver or Connector. 25) if con:
26) con.rollback()
We have to download connector seperately from mysql database. 27) print("There is a problem with sql :",e)
https://dev.mysql.com/downloads/connector/python/2.1.html 28) finally:
29) if cursor:
30) cursor.close()
How to Check Installation: 31) if con:
From python console we have to use help("modules") 32) con.close()
In the list of modules, compulsory MySQL should be there.

Note: In the case of Python3.4 we have to set PATH and PYTHONPATH explicitly Q) Write a Program to Copy Data present in Employees
Table of MySQL Database into Oracle Database
PATH=C:\Python34
PYTHONPATH=C:\Python34\Lib\site-packages 1) import mysql.connector
2) import cx_Oracle
Q) Write a Program to Create Table, Insert Data and display 3) try:
4) con=mysql.connector.connect(host='localhost',database='durgadb',user='root',p
Data by using MySQL Database assword='root')
5) cursor=con.cursor()
1) import mysql.connector 6) cursor.execute("select * from employees")
2) try: 7) data=cursor.fetchall()
3) con=mysql.connector.connect(host='localhost',database='durgadb',user='root',p 8) list=[]
assword='root') 9) for row in data:
4) cursor=con.cursor() 10) t=(row[0],row[1],row[2],row[3])
5) cursor.execute("create table employees(eno int(5) primary key,ename varchar(1 11) list.append(t)
0),esal double(10,2),eaddr varchar(10))") 12) except mysql.connector.DatabaseError as e:

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
163  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
164  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
13) if con:
14) con.rollback()
15) print("There is a problem with MySql :",e)
16) finally:
17) if cursor:
18) cursor.close()
19) if con:
20) con.close()
21)
22) try:
23) con=cx_Oracle.connect('scott/tiger@localhost')
24) cursor=con.cursor()
25) sql="insert into employees values(:eno,:ename,:esal,:eaddr)"
26) cursor.executemany(sql,list)
27) con.commit()
28) print("Records Copied from MySQL Database to Oracle Database Successfully")

29) except cx_Oracle.DatabaseError as e:


30) if con:
31) con.rollback()
REGULAR
EXPRESSIONS
32) print("There is a problem with sql",e)
33) finally:
34) if cursor:
35) cursor.close()
36) if con:
37) con.close()
&
WEB SCRAPING
https://dev.mysql.com/downloads/connector/python/2.1.html

1) create table employees(eno int(5) primary key,ename varchar(10),esal double(10,2


),eaddr varchar(10));
2) insert into employees values(100,'Durga',1000,'Hyd');
3) insert into employees values(200,'Ravi',2000,'Mumbai');
4) insert into employees values(300,'Shiva',3000,'Hyd');

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
165  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
166  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
☕ If we want to represent a group of Strings according to a particular format/pattern The number of occurrences: 3
then we should go for Regular Expressions.
☕ i.e Regualr Expressions is a declarative mechanism to represent a group of Strings Note: We can pass pattern directly as argument to finditer() function.
accroding to particular format/pattern.
☕ Eg 1: We can write a regular expression to represent all mobile numbers 1) import re
☕ Eg 2: We can write a regular expression to represent all mail ids. 2) count=0
3) matcher=re.finditer("ab","abaababa")
4) for match in matcher:
☕ The main important application areas of Regular Expressions are
5) count+=1
1) To develop validation frameworks/validation logic
6) print(match.start(),"...",match.end(),"...",match.group())
2) To develop Pattern matching applications (ctrl-f in windows, grep in UNIX etc)
7) print("The number of occurrences: ",count)
3) To develop Translators like compilers, interpreters etc
4) To develop digital circuits
5) To develop communication protocols like TCP/IP, UDP etc.
Output:
0 ... 2 ... ab
3 ... 5 ... ab
☕ We can develop Regular Expression Based applications by using python module: re
5 ... 7 ... ab
☕ This module contains several inbuilt functions to use Regular Expressions very easily in The number of occurrences: 3
our applications.

1) compile() Character Classes:


We can use character classes to search a group of characters
Returns Module contains compile() Function to compile a Pattern into RegexObject.
pattern = re.compile("ab")
1) [abc]  Either a OR b OR c
2) [^abc]  Except a and b and c
2) finditer(): 3) [a-z]  Any Lower case alphabet symbol
Returns an Iterator object which yields Match object for every Match 4) [A-Z]  Any upper case alphabet symbol
matcher = pattern.finditer("abaababa") 5) [a-zA-Z]  Any alphabet symbol
6) [0-9]  Any digit from 0 to 9
On Match object we can call the following methods. 7) [a-zA-Z0-9]  Any alphanumeric character
1) start()  Returns start index of the match 8) [^a-zA-Z0-9] Except alphanumeric characters(Special Characters)
2) end()  Returns end+1 index of the match
3) group()  Returns the matched string 1) import re
2) matcher=re.finditer("x","a7b@k9z")
1) import re count=0 3) for match in matcher:
2) pattern=re.compile("ab") 4) print(match.start(),"......",match.group())
3) matcher=pattern.finditer("abaababa")
4) for match in matcher: x = [abc] x = [^abc] x = [a-z] x = [0-9] x = [a-zA-Z0-9] x = [^a-zA-Z0-9]
5) count+=1 0 ...... a 1 ...... 7 0 ...... a 1 ...... 7 0 ...... a 3 ...... @
6) print(match.start(),"...",match.end(),"...",match.group()) 2 ...... b 3 ...... @ 2 ...... b 5 ...... 9 1 ...... 7
7) print("The number of occurrences: ",count) 4 ...... k 4 ...... k 2 ...... b
5 ...... 9 6 ...... z 4 ...... k
6 ...... z 5 ...... 9
Output:
6 ...... z
0 ... 2 ... ab
3 ... 5 ... ab
5 ... 7 ... ab

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
167  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
168  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Pre defined Character Classes: Note:
1) \s  Space character 1) ^x  It will check whether target string starts with x OR not.
2) \S  Any character except space character 2) x$  It will check whether target string ends with x OR not.
3) \d  Any digit from 0 to 9
4) \D  Any character except digit
5) \w  Any word character [a-zA-Z0-9]
Important Functions of Remodule:
6) \W  Any character except word character (Special Characters) 1) match()
7) .  Any character including special characters 2) fullmatch()
3) search()
1) import re 4) findall()
2) matcher=re.finditer("x","a7b k@9z") 5) finditer()
3) for match in matcher: 6) sub()
4) print(match.start(),"......",match.group()) 7) subn()
8) split()
x = \s: x = \S: x = \d: x = \D: x = \w: x = \W: x=. 9) compile()
3 ...... 0 ...... a 1 ...... 7 0 ...... a 0 ...... a 3 ...... 0 ...... a
1 ...... 7 6 ...... 9 2 ...... b 1 ...... 7 5 ...... @ 1 ...... 7
2 ...... b 3 ...... 2 ...... b 2 ...... b 1) match():
4 ...... k 4 ...... k 4 ...... k 3 ......  We can use match function to check the given pattern at beginning of target string.
5 ...... @ 5 ...... @ 6 ...... 9 4 ...... k  If the match is available then we will get Match object, otherwise we will get None.
6 ...... 9 7 ...... z 7 ...... z 5 ...... @
7 ...... z 6 ...... 9 1) import re
7 ...... z 2) s=input("Enter pattern to check: ")
3) m=re.match(s,"abcabdefg")
Qunatifiers: 4) if m!= None:
We can use quantifiers to specify the number of occurrences to match. 5) print("Match is available at the beginning of the String")
1) a  Exactly one 'a' 6) print("Start Index:",m.start(), "and End Index:",m.end())
2) a+  Atleast one 'a' 7) else:
3) a*  Any number of a's including zero number 8) print("Match is not available at the beginning of the String")
4) a?  Atmost one 'a' ie either zero number or one number
5) a{m}  Exactly m number of a's Output:
6) a{m,n}  Minimum m number of a's and Maximum n number of a's. D:\python_classes>py test.py
Enter pattern to check: abc
1) import re Match is available at the beginning of the String
2) matcher=re.finditer("x","abaabaaab") Start Index: 0 and End Index: 3
3) for match in matcher:
4) print(match.start(),"......",match.group()) D:\python_classes>py test.py
x = a?:
0 ...... a Enter pattern to check: bde
x = a: x = a+: x = a*: x = a{3}: x = a{2,4}: Match is not available at the beginning of the String
0 ...... a 1 ......
0 ...... a 0 ...... a 5 ...... aaa 2 ...... aa
1 ...... 2 ...... a
2 ...... a 2 ...... aa 5 ...... aaa
3 ...... a 5 ...... aaa 2 ...... aa 3 ...... a 2) fullmatch():
4 ......
5 ...... a 4 ......  We can use fullmatch() function to match a pattern to all of target string. i.e complete
5 ...... aaa 5 ...... a
6 ...... a string should be matched according to given pattern.
8 ...... 6 ...... a
7 ...... a  If complete string matched then this function returns Match object otherwise it
9 ...... 7 ...... a
8 ...... returns None.
9 ......
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
169  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
170  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) import re 4) findall():
2) s=input("Enter pattern to check: ")
 To find all occurrences of the match.
3) m=re.fullmatch(s,"ababab")
 This function returns a list object which contains all occurrences.
4) if m!= None:
5) print("Full String Matched")
1) import re
6) else:
2) l=re.findall("[0-9]","a7b9c5kz")
7) print("Full String not Matched")
3) print(l)

Output:
Output: ['7', '9', '5']
D:\python_classes>py test.py
Enter pattern to check: ab
Full String not Matched 5) finditer():
 Returns the iterator yielding a match object for each match.
D:\python_classes>py test.py  On each match object we can call start(), end() and group() functions.
Enter pattern to check: ababab
Full String Matched 1) import re
2) itr=re.finditer("[a-z]","a7b9c5k8z")
3) search(): 3) for m in itr:
4) print(m.start(),"...",m.end(),"...",m.group())
 We can use search() function to search the given pattern in the target string.
 If the match is available then it returns the Match object which represents first
occurrence of the match. Output: D:\python_classes>py test.py
0 ... 1 ... a
 If the match is not available then it returns None
2 ... 3 ... b
1) import re 4 ... 5 ... c
2) s=input("Enter pattern to check: ") 6 ... 7 ... k
3) m=re.search(s,"abaaaba") 8 ... 9 ... z
4) if m!= None:
5) print("Match is available") 6) sub():
6) print("First Occurrence of match with start index:",m.start(),"and end index:",m.  sub means substitution or replacement.
end())  re.sub(regex,replacement,targetstring)
7) else:  In the target string every matched pattern will be replaced with provided replacement.
8) print("Match is not available")
1) import re
Output: 2) s=re.sub("[a-z]","#","a7b9c5k8z")
D:\python_classes>py test.py 3) print(s)
Enter pattern to check: aaa
Match is available Output: #7#9#5#8#
First Occurrence of match with start index: 2 and end index: 5 Every alphabet symbol is replaced with # symbol

D:\python_classes>py test.py
Enter pattern to check: bbb
7) subn():
 It is exactly same as sub except it can also returns the number of replacements.
Match is not available
 This function returns a tuple where first element is result string and second element is
number of replacements.
(resultstring, number of replacements)
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
171  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
172  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
1) import re 9) ^ symbol:
2) t=re.subn("[a-z]","#","a7b9c5k8z")
 We can use ^ symbol to check whether the given target string starts with our provided
3) print(t)
pattern or not.
4) print("The Result String:",t[0])
5) print("The number of replacements:",t[1])  Eg: res = re.search("^Learn",s)
 If the target string starts with learn then it will return Match object,otherwise returns
Output: None.
D:\python_classes>py test.py
('#7#9#5#8#', 5) test.py
The Result String: #7#9#5#8#
The number of replacements: 5 1) import re
2) s="Learning Python is Very Easy"
3) res=re.search("^Learn",s)
8) split(): 4) if res != None:
 If we want to split the given target string according to a particular pattern then we 5) print("Target String starts with Learn")
should go for split() function. 6) else:
 This function returns list of all tokens. 7) print("Target String Not starts with Learn")

1) import re Output: Target String starts with Learn


2) l=re.split(",","sunny,bunny,chinny,vinny,pinny")
3) print(l)
4) for t in l: 10) $ symbol:
5) print(t)  We can use $ symbol to check whether the given target string ends with our
provided pattern or not.
Output:  Eg: res = re.search("Easy$",s)
D:\python_classes>py test.py  If the target string ends with Easy then it will return Match object,otherwise
['sunny', 'bunny', 'chinny', 'vinny', 'pinny'] returns None.
sunny
bunny test.py
chinny
vinny 1) import re
pinny 2) s="Learning Python is Very Easy"
3) res=re.search("Easy$",s)
1) import re 4) if res != None:
2) l=re.split("\.","www.durgasoft.com") 5) print("Target String ends with Easy")
3) for t in l: 6) else:
4) print(t) 7) print("Target String Not ends with Easy")

Output: Output: Target String ends with Easy


D:\python_classes>py test.py
www Note: If we want to ignore case then we have to pass 3rd argument re.IGNORECASE for
durgasoft search() function.
com
Eg: res = re.search("easy$",s,re.IGNORECASE)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
173  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
174  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
test.py App 3) Write a Regular Expression to represent all 10 Digit
1) import re Mobile Numbers
2) s="Learning Python is Very Easy" Rules:
3) res=re.search("easy$",s,re.IGNORECASE) 1) Every Number should contains exactly 10 Digits
4) if res != None: 2) The 1st Digit should be 7 OR 8 OR 9
5) print("Target String ends with Easy by ignoring case")
6) else: [7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]
7) print("Target String Not ends with Easy by ignoring case") OR
[7-9][0-9]{9}
Output: Target String ends with Easy by ignoring case OR
[7-9]\d{9}
App 1) Write a Regular Expression to represent all Yava
Language Identifiers App 4) Write a Python Program to check whether the given
Rules: Number is valid Mobile Number OR not?
1) The allowed characters are a-z,A-Z,0-9,#
2) The first character should be a lower case alphabet symbol from a to k 1) import re
3) The second character should be a digit divisible by 3 2) n=input("Enter number:")
4) The length of identifier should be atleast 2. 3) m=re.fullmatch("[7-9]\d{9}",n)
[a-k][0369][a-zA-Z0-9#]* 4) if m!= None:
5) print("Valid Mobile Number")
6) else:
App 2) Write a Python Program to check whether the given 7) print("Invalid Mobile Number")
String is Yava Language Identifier OR not?
Output
1) import re D:\python_classes>py test.py
2) s=input("Enter Identifier:") Enter number:9898989898
3) m=re.fullmatch("[a-k][0369][a-zA-Z0-9#]*",s) Valid Mobile Number
4) if m!= None:
5) print(s,"is valid Yava Identifier") D:\python_classes>py test.py
6) else: Enter number:6786786787
7) print(s,"is invalid Yava Identifier") Invalid Mobile Number

Output D:\python_classes>py test.py


D:\python_classes>py test.py Enter number:898989
Enter Identifier:a6kk9z## Invalid Mobile Number
a6kk9z## is valid Yava Identifier
App 5) Write a Python Program to extract all Mobile Numbers present in
D:\python_classes>py test.py input.txt where Numbers are mixed with Normal Text Data
Enter Identifier:k9b876
k9b876 is valid Yava Identifier 1) import re
D:\python_classes>py test.py 2) f1=open("input.txt","r")
Enter Identifier:k7b9 3) f2=open("output.txt","w")
k7b9 is invalid Yava Identifier
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
175  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
176  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
4) for line in f1: 6) else:
5) list=re.findall("[7-9]\d{9}",line) 7) print("Invalid Mail id")
6) for n in list:
7) f2.write(n+"\n") Output:
8) print("Extracted all Mobile Numbers into output.txt") D:\python_classes>py test.py
9) f1.close() Enter Mail id:[email protected]
10) f2.close() Valid Mail Id

Web Scraping by using Regular Expressions D:\python_classes>py test.py


Enter Mail id:durgatoc
The process of collecting information from web pages is called web scraping. In web Invalid Mail id
scraping to match our required patterns like mail ids, mobile numbers we can use regular
expressions. D:\python_classes>py test.py
Enter Mail id:[email protected]
1) import re,urllib Invalid Mail id
2) import urllib.request
3) sites="google rediff".split() Write a Python Program to check whether given Car Registration
4) print(sites)
5) for s in sites: Number is valid Telangana State Registration Number OR not?
6) print("Searching...",s)
7) u=urllib.request.urlopen("http://"+s+".com") 1) import re
8) text=u.read() 2) s=input("Enter Vehicle Registration Number:")
9) title=re.findall("<title>.*</title>",str(text),re.I) 3) m=re.fullmatch("TS[012][0-9][A-Z]{2}\d{4}",s)
10) print(title[0]) 4) if m!=None:
5) print("Valid Vehicle Registration Number");
6) else:
Program to get all Phone Numbers of redbus.in by using Web 7) print("Invalid Vehicle Registration Number")
Scraping and Regular Expressions
Output:
1) import re,urllib D:\python_classes>py test.py
2) import urllib.request Enter Vehicle Registration Number:TS07EA7777
3) u=urllib.request.urlopen("https://www.redbus.in/info/contactus") Valid Vehicle Registration Number
4) text=u.read()
5) numbers=re.findall("[0-9-]{7}[0-9-]+",str(text),re.I) D:\python_classes>py test.py
6) for n in numbers: Enter Vehicle Registration Number:TS07KF0786
7) print(n) Valid Vehicle Registration Number

Write a Python Program to check whether the given mail id is valid D:\python_classes>py test.py
gmail id OR not? Enter Vehicle Registration Number:AP07EA7898
Invalid Vehicle Registration Number
1) import re
2) s=input("Enter Mail id:")
3) m=re.fullmatch("\w[a-zA-Z0-9_.]*@gmail[.]com",s)
4) if m!=None:
5) print("Valid Mail Id");

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
177  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
178  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Python Program to check whether the given Mobile Number is valid
OR not (10 Digit OR 11 Digit OR 12 Digit)
1) import re
2) s=input("Enter Mobile Number:")
3) m=re.fullmatch("(0|91)?[7-9][0-9]{9}",s)
4) if m!=None:
5) print("Valid Mobile Number");
6) else:
7) print("Invalid Mobile Number")

Summary Table and some more Examples.

DECORATOR
FUNCTIONS

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
179  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
180  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Decorator is a function which can take a function as argument and extend its functionality Hello Sunny Bad Morning
and returns modified function with extended functionality. In the above program whenever we call wish() function automatically decor function will
be executed.
Input Function new(add some functionality)
Decorator
wish() How to call Same Function with Decorator and without Decorator:
inner()
We should not use @decor

Input Function Decorator Output Function with 1) def decor(func):


Function extended Functionality 2) def inner(name):
3) if name=="Sunny":
4) print("Hello Sunny Bad Morning")
The main objective of decorator functions is we can extend the functionality of existing 5) else:
functions without modifies that function. 6) func(name)
7) return inner
1) def wish(name): 8)
2) print("Hello",name,"Good Morning") 9) def wish(name):
10) print("Hello",name,"Good Morning")
This function can always print same output for any name 11)
12) decorfunction=decor(wish)
Hello Durga Good Morning 13)
Hello Ravi Good Morning 14) wish("Durga") #decorator wont be executed
Hello Sunny Good Morning 15) wish("Sunny") #decorator wont be executed
16)
But we want to modify this function to provide different message if name is Sunny. 17) decorfunction("Durga")#decorator will be executed
We can do this without touching wish() function by using decorator. 18) decorfunction("Sunny")#decorator will be executed
1) def decor(func):
Output
2) def inner(name):
Hello Durga Good Morning
3) if name=="Sunny":
Hello Sunny Good Morning
4) print("Hello Sunny Bad Morning")
Hello Durga Good Morning
5) else:
Hello Sunny Bad Morning
6) func(name)
7) return inner
1) def smart_division(func):
8)
2) def inner(a,b):
9) @decor
3) print("We are dividing",a,"with",b)
10) def wish(name):
4) if b==0:
11) print("Hello",name,"Good Morning")
5) print("OOPS...cannot divide")
12)
6) return
13) wish("Durga")
7) else:
14) wish("Ravi")
8) return func(a,b)
15) wish("Sunny")
9) return inner
10)
Output 11) @smart_division
Hello Durga Good Morning 12) def division(a,b):
Hello Ravi Good Morning 13) return a/b
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
181  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
182  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
14) print(division(20,2)) 1) def decor1(func):
15) print(division(20,0)) 2) def inner():
3) x=func()
Without Decorator we will get Error. In this Case Output is: 4) return x*x
10.0 5) return inner
Traceback (most recent call last): 6)
File "test.py", line 16, in <module> 7) def decor(func):
print(division(20,0)) 8) def inner():
File "test.py", line 13, in division 9) x=func()
return a/b 10) return 2*x
ZeroDivisionError: division by zero 11) return inner
12)
13) @decor1
With Decorator we won't get any Error. In this Case Output is: 14) @decor
We are dividing 20 with 2 15) def num():
10.0 16) return 10
We are dividing 20 with 0 17)
OOPS...cannot divide 18) print(num())
None

1) def marriagedecor(func):
2) def inner():
3) print('Hair decoration...')
4) print('Face decoration with Platinum package')
5) print('Fair and Lovely etc..')
6) func()
7) return inner
8)
9) def getready():
10) print('Ready for the marriage')
11)
12) decorated_getready=marriagedecor(getready)
13)
14) decorated_getready()

Decorator Chaining
We can define multiple decorators for the same function and all these decorators will
form Decorator Chaining.
Eg:
@decor1
@decor
def num():

For num() function we are applying 2 decorator functions. First inner decorator will work
and then outer decorator.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
183  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
184  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Generator is a function which is responsible to generate a sequence of values.
We can write generator functions just like ordinary functions, but it uses yield keyword to
return values.

Generator A Sequence of Values


Function

yield

1) def mygen():
2) yield 'A'
3) yield 'B'
4) yield 'C'
5)

GENERATOR
6) g=mygen()
7) print(type(g))
8)
9) print(next(g))
10) print(next(g))
11) print(next(g))
12) print(next(g))

FUNCTIONS
Output
<class 'generator'>
A
B
C
Traceback (most recent call last):
File "test.py", line 12, in <module>
print(next(g))
StopIteration

1) def countdown(num):
2) print("Start Countdown")
3) while(num>0):
4) yield num
5) num=num-1
6) values=countdown(5)
7) for x in values:
8) print(x)

Output
Start Countdown
5

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
185  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
186  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
4 Output
3 0
2 1
1 1
2
Eg 3: To generate first n numbers 3
5
1) def firstn(num): 8
2) n=1 13
3) while n<=num: 21
4) yield n 34
5) n=n+1 55
6) 89
7) values=firstn(5)
8) for x in values:
9) print(x)
Advantages of Generator Functions:
1) When compared with Class Level Iterators, Generators are very easy to use.
Output 2) Improves Memory Utilization and Performance.
3) Generators are best suitable for reading Data from Large Number of Large Files.
1
4) Generators work great for web scraping and crawling.
2
3
4 Generators vs Normal Collections wrt Performance:
5
1) import random
We can convert generator into list as follows: 2) import time
values = firstn(10) 3)
l1 = list(values) 4) names = ['Sunny','Bunny','Chinny','Vinny']
print(l1) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 5) subjects = ['Python','Java','Blockchain']
6)
Eg 4: To generate Fibonacci Numbers... 7) def people_list(num_people):
The next is the sum of previous 2 numbers 8) results = []
9) for i in range(num_people):
Eg: 0,1,1,2,3,5,8,13,21,... 10) person = {
11) 'id':i,
1) def fib(): 12) 'name': random.choice(names),
2) a,b=0,1 13) 'subject':random.choice(subjects)
3) while True: 14) }
4) yield a 15) results.append(person)
5) a,b=b,a+b 16) return results
6) for f in fib(): 17)
7) if f>100: 18) def people_generator(num_people):
8) break 19) for i in range(num_people):
9) print(f) 20) person = {
21) 'id':i,
22) 'name': random.choice(names),
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
187  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
188  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
23) 'major':random.choice(subjects)
24) }
25) yield person
26)
27) '''''t1 = time.clock()
28) people = people_list(10000000)
29) t2 = time.clock()'''
30)
31) t1 = time.clock()
32) people = people_generator(10000000)
33) t2 = time.clock()
34)
35) print('Took {}'.format(t2-t1))

Note: In the above program observe the differnce wrt execution time by using list and
generators

Generators vs Normal Collections wrt Memory Utilization:


Normal Collection:
l=[x*x for x in range(10000000000000000)]
print(l[0])
ASSERTIONS
We will get MemoryError in this case because all these values are required to store in the
memory.

Generators:
g=(x*x for x in range(10000000000000000))
print(next(g))

Output: 0

We won't get any MemoryError because the values won't be stored at the beginning

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
189  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
190  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
14) AssertionError: The square of 3 should be 9
Debugging Python Program by using assert Keyword: 15)
☕ The process of identifying and fixing the bug is called debugging. 16) def squareIt(x):
☕ Very common way of debugging is to use print() statement. But the problem with the 17) return x*x
print() statement is after fixing the bug,compulsory we have to delete the extra added 18) assert squareIt(2)==4,"The square of 2 should be 4"
print() statments,otherwise these will be executed at runtime which creates 19) assert squareIt(3)==9,"The square of 3 should be 9"
performance problems and disturbs console output. 20) assert squareIt(4)==16,"The square of 4 should be 16"
☕ To overcome this problem we should go for assert statement. The main advantage of 21) print(squareIt(2))
assert statement over print() statement is after fixing bug we are not required to 22) print(squareIt(3))
delete assert statements. Based on our requirement we can enable or disable assert 23) print(squareIt(4))
statements.
☕ Hence the main purpose of assertions is to perform debugging. Usully we can perform Output
debugging either in development or in test environments but not in production 4
environment. Hence assertions concept is applicable only for dev and test 9
environments but not for production environment. 16

Types of assert Statements: Exception Handling vs Assertions:


There are 2 types of assert statements Assertions concept can be used to alert programmer to resolve development time errors.
1) Simple Version Exception Handling can be used to handle runtime errors.
2) Augmented Version

1) Simple Version:
assert conditional_expression

2) Augmented Version:
 assert conditional_expression, message
 conditional_expression will be evaluated and if it is true then the program will be
continued.
 If it is false then the program will be terminated by raising AssertionError.
 By seeing AssertionError, programmer can analyze the code and can fix the problem.

1) def squareIt(x):
2) return x**x
3) assert squareIt(2)==4,"The square of 2 should be 4"
4) assert squareIt(3)==9,"The square of 3 should be 9"
5) assert squareIt(4)==16,"The square of 4 should be 16"
6) print(squareIt(2))
7) print(squareIt(3))
8) print(squareIt(4))
9)
10) D:\Python_classes>py test.py
11) Traceback (most recent call last):
12) File "test.py", line 4, in <module>
13) assert squareIt(3)==9,"The square of 3 should be 9"

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
191  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
192  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
It is highly recommended to store complete application flow and exceptions information
to a file. This process is called logging.

The main advanatages of logging are:


1) We can use log files while performing debugging
2) We can provide statistics like number of requests per day etc

To implement logging, Python provides inbuilt module logging.

Logging Levels:
Depending on type of information, logging data is divided according to the following 6
levels in python

1) CRITICAL  50
Represents a very serious problem that needs high attention

PYTHON
2) ERROR  40
Represents a serious error

3) WARNING  30
Represents a warning message, some caution needed. It is alert to the programmer.

4) INFO  20

LOGGING
Represents a message with some important information

5) DEBUG  10
Represents a message with debugging information

6) NOTSET  0
Represents that level is not set

By default while executing Python program only WARNING and higher level messages will
be displayed.

How to implement Logging:


To perform logging, first we required to create a file to store messages and we have to
specify which level messages required to store.

We can do this by using basicConfig() function of logging module.


logging.basicConfig(filename='log.txt',level=logging.WARNING)

The above line will create a file log.txt and we can store either WARNING level or higher
level messages to that file.

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
193  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
194  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
After creating log file, we can write messages to that file by using the following methods
☕ logging.debug(message)
How to configure Log File in over writing Mode:
In the above program by default data will be appended to the log file.i.e append is the
☕ logging.info(message)
default mode. Instead of appending if we want to over write data then we have to use
☕ logging.warning(message) filemode property.
☕ logging.error(message)
☕ logging.critical(message) logging.basicConfig(filename='log786.txt',level=logging.WARNING)
Meant for appending
Q) Write a Python Program to create a Log File and write WARNING and
Higher Level Messages? logging.basicConfig(filename='log786.txt',level=logging.WARNING,filemode='a')
Explicitly we are specifying appending.
1) import logging
2) logging.basicConfig(filename='log.txt',level=logging.WARNING) logging.basicConfig(filename='log786.txt',level=logging.WARNING,filemode='w')
3) print('Logging Demo') Meant for over writing of previous data.
4) logging.debug('Debug Information')
5) logging.info('info Information') Note:
6) logging.warning('warning Information') logging.basicConfig(filename='log.txt',level=logging.DEBUG)
7) logging.error('error Information') If we are not specifying level then the default level is WARNING(30)
8) logging.critical('critical Information') If we are not specifying file name then the messages will be printed to the console.

log.txt: test.py
WARNING:root:warning Information
ERROR:root:error Information 1) import logging
CRITICAL:root:critical Information 2) logging.basicConfig()
3) print('Logging Demo')
Note: In the above program only WARNING and higher level messages will be written to 4) logging.debug('Debug Information')
the log file. If we set level as DEBUG then all messages will be written to the log file. 5) logging.info('info Information')
6) logging.warning('warning Information')
test.py 7) logging.error('error Information')
8) logging.critical('critical Information')
1) import logging
2) logging.basicConfig(filename='log.txt',level=logging.DEBUG) D:\durgaclasses>py test.py
3) print('Logging Demo') Logging Demo
4) logging.debug('Debug Information') WARNING:root:warning Information
5) logging.info('info Information') ERROR:root:error Information
6) logging.warning('warning Information') CRITICAL:root:critical Information
7) logging.error('error Information')
8) logging.critical('critical Information') How to Format Log Messages:
By using format keyword argument, we can format messages.
log.txt
DEBUG:root:Debug Information 1) To display only level name: logging.basicConfig(format='%(levelname)s')
INFO:root:info Information Output
WARNING:root:warning Information WARNING
ERROR:root:error Information ERROR
CRITICAL:root:critical Information CRITICAL
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
195  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
196  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
2) To display levelname and message: How to write Python Program Exceptions to the Log File:
logging.basicConfig(format='%(levelname)s:%(message)s')
By using the following function we can write exception information to the log file.
Output logging.exception(msg)
WARNING:warning Information
ERROR:error Information
CRITICAL:critical Information Q) Python Program to write Exception Information to the Log File
1) import logging
How to add Timestamp in the Log Messages: 2) logging.basicConfig(filename='mylog.txt',level=logging.INFO,format='%(asctime)s:
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s') %(levelname)s:%(message)s',datefmt='%d/%m/%Y %I:%M:%S %p')
3) logging.info('A new Request Came')
Output 4) try:
2018-06-15 11:50:08,325:WARNING:warning Information 5) x=int(input('Enter First Number:'))
2018-06-15 11:50:08,372:ERROR:error Information 6) y=int(input('Enter Second Number:'))
2018-06-15 11:50:08,372:CRITICAL:critical Information 7) print('The Result:',x/y)
8)
How to Change Date and Time Format: 9) except ZeroDivisionError as msg:
We have to use special keyword argument: datefmt 10) print('cannot divide with zero')
11) logging.exception(msg)
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', 12)
datefmt='%d/%m/%Y %I:%M:%S %p') 13) except ValueError as msg:
datefmt='%d/%m/%Y %I:%M:%S %p'  Case is important 14) print('Please provide int values only')
15) logging.exception(msg)
16)
Output
17) logging.info('Request Processing Completed')
15/06/2018 12:04:31 PM:WARNING:warning Information
15/06/2018 12:04:31 PM:ERROR:error Information
D:\durgaclasses>py test.py
15/06/2018 12:04:31 PM:CRITICAL:critical Information Enter First Number:10
Enter Second Number:2
Note: The Result: 5.0
%I  means 12 Hours time scale
%H  means 24 Hours time scale D:\durgaclasses>py test.py
Enter First Number:20
Eg: logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', Enter Second Number:2
datefmt='%d/%m/%Y %H:%M:%S') The Result: 10.0

Output: D:\durgaclasses>py test.py


15/06/2018 12:06:28:WARNING:warning Information Enter First Number:10
15/06/2018 12:06:28:ERROR:error Information Enter Second Number:0
15/06/2018 12:06:28:CRITICAL:critical Information cannot divide with zero

https://docs.python.org/3/library/logging.html#logrecord-attributes D:\durgaclasses>py test.py


https://docs.python.org/3/library/time.html#time.strftime Enter First Number:ten
Please provide int values only

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
197  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
198  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
mylog.txt In the above application the configurations performed in test module won't be reflected,
15/06/2018 12:30:51 PM:INFO:A new Request Came because root logger is already configured in student module.
15/06/2018 12:30:53 PM:INFO:Request Processing Completed
15/06/2018 12:30:55 PM:INFO:A new Request Came Need of Our Own Customized Logger:
15/06/2018 12:31:00 PM:INFO:Request Processing Completed
The problems with root logger are:
15/06/2018 12:31:02 PM:INFO:A new Request Came
15/06/2018 12:31:05 PM:ERROR:division by zero
1) Once we set basic configuration then that configuration is final and we cannot change.
Traceback (most recent call last):
2) It will always work for only one handler at a time, either console or file, but not both
File "test.py", line 7, in <module>
simultaneously.
print('The Result:',x/y)
3) It is not possible to configure logger with different configurations at different levels.
ZeroDivisionError: division by zero
4) We cannot specify multiple log files for multiple modules/classes/methods.
15/06/2018 12:31:05 PM:INFO:Request Processing Completed
15/06/2018 12:31:06 PM:INFO:A new Request Came To overcome these problems we should go for our own customized loggers
15/06/2018 12:31:10 PM:ERROR:invalid literal for int() with base 10: 'ten'
Traceback (most recent call last):
File "test.py", line 5, in <module> Advanced logging Module Features: Logger:
x=int(input('Enter First Number:')) Logger is more advanced than basic logging.
ValueError: invalid literal for int() with base 10: 'ten' It is highly recommended to use and it provides several extra features.
15/06/2018 12:31:10 PM:INFO:Request Processing Completed
Steps for Advanced Logging:
Problems with Root Logger:
If we are not defining our own logger,then bydefault root logger will be considered. 1) Creation of Logger object and set log level.
Once we perform basic configuration to root logger then the configurations are fixed and logger = logging.getLogger('demologger')
we cannot change. logger.setLevel(logging.INFO)

Demo Application: 2) Creation of Handler object and set log level.

student.py: 3) There are several types of Handlers like StreamHandler, FileHandler etc.
consoleHandler = logging.StreamHandler()
1) import logging consoleHandler.setLevel(logging.INFO)
2) logging.basicConfig(filename='student.log',level=logging.INFO)
3) logging.info('info message from student module') Note: If we use StreamHandler then log messages will be printed to console.

test.py: 4) Creation of Formatter Object.


formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s',
1) import logging datefmt = '%d/%m/%Y %I:%M:%S %p')
2) import student
3) logging.basicConfig(filename='test.log',level=logging.DEBUG) 5) Add Formatter to Handler  consoleHandler.setFormatter(formatter)
4) logging.debug('debug message from test module')
6) Add Handler to Logger  logger.addHandler(consoleHandler)
student.log:
INFO: root:info message from student module 7) Write messages by using logger object and the following methods
logger.debug('debug message')
logger.info('info message')

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
199  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
200  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
logger.warn('warn message') 16) logger.debug('debug message')
logger.error('error message') 17) logger.info('info message')
logger.critical('critical message') 18) logger.warn('warn message')
19) logger.error('error message')
Note: Bydefault logger will set to WARNING level. But we can set our own level based on 20) logger.critical('critical message')
our requirement. 21)
logger = logging.getLogger('demologger') 22) demo = LoggerDemoConsole()
logger.setLevel(logging.INFO) 23) demo.testLog()

logger log level by default available to console and file handlers. If we are not satisfied D:\durgaclasses>py loggingdemo3.py
with logger level, then we can set log level explicitly at console level and file levels. 06/18/2018 12:14:15 PM - demologger - INFO: info message
06/18/2018 12:14:15 PM - demologger - WARNING: warn message
consoleHandler = logging.StreamHandler() 06/18/2018 12:14:15 PM - demologger - ERROR: error message
consoleHandler.setLevel(logging.WARNING) 06/18/2018 12:14:15 PM - demologger - CRITICAL: critical message

fileHandler = logging.FileHandler('abc.log',mode='a') Note: If we want to use class name as logger name then we have to create logger object
fileHandler.setLevel(logging.ERROR) as follows logger = logging.getLogger(LoggerDemoConsole.__name__)

Note: console and file log levels should be supported by logger. i.e logger log level should In this case output is:
be lower than console and file levels. Otherwise only logger log level will be considered.
D:\durgaclasses>py loggingdemo3.py
Eg: 06/18/2018 12:21:00 PM - LoggerDemoConsole - INFO: info message
logger  DEBUG console  INFO  Valid and INFO will be considered 06/18/2018 12:21:00 PM - LoggerDemoConsole - WARNING: warn message
logger  INFO console  DEBUG  Invalid and only INFO will be considered to the 06/18/2018 12:21:00 PM - LoggerDemoConsole - ERROR: error message
console. 06/18/2018 12:21:00 PM - LoggerDemoConsole - CRITICAL: critical message

Demo Program for File Handler:


Demo Program for Console Handler:
1) import logging
1) import logging 2) class LoggerDemoConsole:
2) class LoggerDemoConsole: 3)
3) 4) def testLog(self):
4) def testLog(self): 5) logger = logging.getLogger('demologger')
5) logger = logging.getLogger('demologger') 6) logger.setLevel(logging.INFO)
6) logger.setLevel(logging.INFO) 7)
7) 8) fileHandler = logging.FileHandler('abc.log',mode='a')
8) consoleHandler = logging.StreamHandler() 9) fileHandler.setLevel(logging.INFO)
9) consoleHandler.setLevel(logging.INFO) 10)
10) 11) formatter = logging.Formatter('%(asctime)s - %(name)s -
11) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s: %(message)s',
%(levelname)s: %(message)s', 12) datefmt='%m/%d/%Y %I:%M:%S %p')
12) datefmt='%m/%d/%Y %I:%M:%S %p') 13)
13) 14) fileHandler.setFormatter(formatter)
14) consoleHandler.setFormatter(formatter) 15) logger.addHandler(fileHandler)
15) logger.addHandler(consoleHandler) 16)
nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
201  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
202  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
17) logger.debug('debug message') [handler_fileHandler]
18) logger.info('info message') class=FileHandler
19) logger.warn('warn message') level=DEBUG
20) logger.error('error message') formatter=simpleFormatter
21) logger.critical('critical message') args=('test.log', 'w')
22)
23) demo = LoggerDemoConsole() [formatter_simpleFormatter]
24) demo.testLog() format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%m/%d/%Y %I:%M:%S %p
abc.log:
07/05/2018 08:58:04 AM - demologger - INFO: info message test.py
07/05/2018 08:58:04 AM - demologger - WARNING: warn message
07/05/2018 08:58:04 AM - demologger - ERROR: error message 1) import logging
07/05/2018 08:58:04 AM - demologger - CRITICAL: critical message 2) import logging.config
3) class LoggerDemoConf():
4) def testLog(self):
Logger with Configuration File: 5) logging.config.fileConfig('logging.conf')
In the above program, everything we hard coded in the python script. It is not a good 6) logger = logging.getLogger(LoggerDemoConf.__name__)
programming practice. We will configure all the required things inside a configuration file
7)
and we can use this file directly in our program.
8) logger.debug('debug message')
9) logger.info('info message')
logging.config.fileConfig('logging.conf')
10) logger.warn('warn message')
logger = logging.getLogger(LoggerDemoConf.__name__)
11) logger.error('error message')
12) logger.critical('critical message')
Note: The extension of the file need not be conf. We can use any extension like txt or 13)
durga etc. 14) demo = LoggerDemoConf()
15) demo.testLog()
logging.conf
[loggers] test.log
keys=root,LoggerDemoConf 06/18/2018 12:40:05 PM - LoggerDemoConf - DEBUG - debug message
06/18/2018 12:40:05 PM - LoggerDemoConf - INFO - info message
[handlers] 06/18/2018 12:40:05 PM - LoggerDemoConf - WARNING - warn message
keys=fileHandler 06/18/2018 12:40:05 PM - LoggerDemoConf - ERROR - error message
06/18/2018 12:40:05 PM - LoggerDemoConf - CRITICAL - critical message
[formatters]
keys=simpleFormatter Case-1: To set log level as INFO
[logger_root] [handler_fileHandler]
level=DEBUG class=FileHandler
handlers=fileHandler level=INFO
formatter=simpleFormatter
[logger_LoggerDemoConf] args=('test.log', 'w')
level=DEBUG
handlers=fileHandler
qualname=demoLogger

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
203  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
204  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
Case-2: To set Append Mode 13) logger.debug('m2:debug message')
14) logger.info('m2:info message')
[handler_fileHandler] 15) logger.warn('m2:warn message')
class=FileHandler 16) logger.error('m2:error message')
level=INFO 17) logger.critical('m2:critical message')
formatter=simpleFormatter 18) def m3(self):
args=('test.log', 'a') 19) logger=getCustomLogger(logging.ERROR)
20) logger.debug('m3:debug message')
21) logger.info('m3:info message')
Creation of Custom Logger: 22) logger.warn('m3:warn message')
23) logger.error('m3:error message')
customlogger.py 24) logger.critical('m3:critical message')
25)
1) import logging 26) l=LoggingDemo()
2) import inspect 27) print('Custom Logger Demo')
3) def getCustomLogger(level): 28) l.m1()
4) # Get Name of class/method from where this method called 29) l.m2()
5) loggername=inspect.stack()[1][3] 30) l.m3()
6) logger=logging.getLogger(loggername)
7) logger.setLevel(level) abc.log:
8) 06/19/2018 12:17:19 PM - m1 - DEBUG: m1:debug message
9) fileHandler=logging.FileHandler('abc.log',mode='a') 06/19/2018 12:17:19 PM - m1 - INFO: m1:info message
10) fileHandler.setLevel(level) 06/19/2018 12:17:19 PM - m1 - WARNING: m1:warn message
11) 06/19/2018 12:17:19 PM - m1 - ERROR: m1:error message
12) formatter = logging.Formatter('%(asctime)s - %(name)s - 06/19/2018 12:17:19 PM - m1 - CRITICAL: m1:critical message
%(levelname)s: %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p') 06/19/2018 12:17:19 PM - m2 - WARNING: m2:warn message
13) fileHandler.setFormatter(formatter) 06/19/2018 12:17:19 PM - m2 - ERROR: m2:error message
14) logger.addHandler(fileHandler) 06/19/2018 12:17:19 PM - m2 - CRITICAL: m2:critical message
15) 06/19/2018 12:17:19 PM - m3 - ERROR: m3:error message
16) return logger 06/19/2018 12:17:19 PM - m3 - CRITICAL: m3:critical message

test.py
How to Create seperate Log File based on Caller:
1) import logging
2) from customlogger import getCustomLogger 1) import logging
3) class LoggingDemo: 2) import inspect
4) def m1(self): 3) def getCustomLogger(level):
5) logger=getCustomLogger(logging.DEBUG) 4) loggername=inspect.stack()[1][3]
6) logger.debug('m1:debug message') 5) logger=logging.getLogger(loggername)
7) logger.info('m1:info message') 6) logger.setLevel(level)
8) logger.warn('m1:warn message') 7)
9) logger.error('m1:error message') 8) fileHandler=logging.FileHandler('{}.log'.format(loggername),mode='a')
10) logger.critical('m1:critical message') 9) fileHandler.setLevel(level)
11) def m2(self): 10)
12) logger=getCustomLogger(logging.WARNING)

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
205  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
206  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
11) formatter = logging.Formatter('%(asctime)s - %(name)s - 06/19/2018 12:26:04 PM - m1 - ERROR: m1:error message
%(levelname)s: %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p') 06/19/2018 12:26:04 PM - m1 - CRITICAL: m1:critical message
12) fileHandler.setFormatter(formatter)
13) logger.addHandler(fileHandler) m2.log
14) 06/19/2018 12:26:04 PM - m2 - WARNING: m2:warn message
15) return logger 06/19/2018 12:26:04 PM - m2 - ERROR: m2:error message
06/19/2018 12:26:04 PM - m2 - CRITICAL: m2:critical message
test.py:
#Same as previous m3.log
06/19/2018 12:26:04 PM - m3 - ERROR: m3:error message
1) import logging 06/19/2018 12:26:04 PM - m3 - CRITICAL: m3:critical message
2) from customlogger import getCustomLogger
3) class LoggingDemo:
4) def m1(self): Advantages of Customized Logger:
5) logger=getCustomLogger(logging.DEBUG) 1) We can reuse same customlogger code where ever logger required.
6) logger.debug('m1:debug message') 2) For every caller we can able to create a seperate log file
7) logger.info('m1:info message') 3) For different handlers we can set different log levels.
8) logger.warn('m1:warn message')
9) logger.error('m1:error message') Another Example for Custom Handler:
10) logger.critical('m1:critical message')
11) def m2(self):
customlogger.py:
12) logger=getCustomLogger(logging.WARNING)
13) logger.debug('m2:debug message')
1) import logging
14) logger.info('m2:info message')
2) import inspect
15) logger.warn('m2:warn message')
3) def getCustomLogger(level):
16) logger.error('m2:error message')
4) loggername=inspect.stack()[1][3]
17) logger.critical('m2:critical message')
5)
18) def m3(self):
6) logger=logging.getLogger(loggername)
19) logger=getCustomLogger(logging.ERROR)
7) logger.setLevel(level)
20) logger.debug('m3:debug message')
8) fileHandler=logging.FileHandler('test.log',mode='a')
21) logger.info('m3:info message')
9) fileHandler.setLevel(level)
22) logger.warn('m3:warn message')
10) formatter=logging.Formatter('%(asctime)s - %(name)s -
23) logger.error('m3:error message')
%(levelname)s: %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
24) logger.critical('m3:critical message')
11) fileHandler.setFormatter(formatter)
25)
12) logger.addHandler(fileHandler)
26) l=LoggingDemo()
13) return logger
27) print('Logging Demo with Seperate Log File')
28) l.m1()
29) l.m2()
test.py
30) l.m3()
1) import logging
2) from customlogger import getCustomLogger
m1.log 3) class Test:
06/19/2018 12:26:04 PM - m1 - DEBUG: m1:debug message
4) def logtest(self):
06/19/2018 12:26:04 PM - m1 - INFO: m1:info message
5) logger=getCustomLogger(logging.DEBUG)
06/19/2018 12:26:04 PM - m1 - WARNING: m1:warn message

nd nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038, DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
207  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
208  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com
6) logger.debug('debug message')
7) logger.info('info message')
8) logger.warning('warning message')
9) logger.error('error message')
10) logger.critical('critical message')
11) t=Test()
12) t.logtest()

student.py:

1) import logging
2) from customlogger import getCustomLogger
3) def studentfunction():
4) logger=getCustomLogger(logging.ERROR)
5) logger.debug('debug message')
6) logger.info('info message')
7) logger.warning('warning message')
8) logger.error('error message')
9) logger.critical('critical message')
10) studentfunction()

Note: we can disable a partcular level of logging as follows:


logging.disable(logging.CRITICAL)

nd
DURGASOFT, # 202, 2 Floor, HUDA Maitrivanam, Ameerpet, Hyderabad - 500038,
209  040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 | www.durgasoft.com

You might also like