OOPS Part 1 Advanced Python Durga PDF
OOPS Part 1 Advanced Python Durga PDF
Part -
1
1 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet,
Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 |
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.
Syntax:
class className:
''' documenttation string '''
variables:instance variables,static and local variables
methods: instance methods,static methods,class methods
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)
1) Instance Methods
2) Class Methods
3) Static Methods
1) class Student:
2) '''''Developed by durga for python demo'''
3) def init (self):
4) self.name='durga'
5) self.age=40
6) self.marks=80
7)
8) def talk(self):
9) print("Hello I am :",self.name)
10) print("My Age is:",self.age)
11) print("My Marks are:",self.marks)
What is Object:
Pysical existence of a class is nothing but object. We can create any number of objects for a
class.
Example: s = Student()
Program: Write a Python program to create a Student class and Creates an object to it. Call
the method talk() to display student details
1) class Student:
2)
3) def init (self,name,rollno,marks):
4) self.name=name
5) self.rollno=rollno
6) self.marks=marks
7)
Output:
D:\durgaclasses>py test.py
Hello My Name is: Durga
My Rollno is: 101
My Marks are: 80
Self Variable:
self is the default variable which is always pointing to current object (like this
keyword in Java)
By using self we can access instance variables and instance methods of object.
Note:
1) self should be first parameter inside
constructor def init (self):
2) self should be first parameter inside instance
methods def talk(self):
Constructor Concept:
☕ 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.
☕ The main purpose of constructor is to declare and initialize instance variables.
☕ Per object constructor will be exeucted only once.
☕ Constructor can take atleast one argument(atleast self)
☕ Constructor is optional and if we are not providing any constructor then python will
provide default constructor.
Example:
1) class Test:
2)
3) def init (self):
4) print("Constructor exeuction...")
5)
6) def m1(self):
7) print("Method execution...")
8)
9) t1=Test()
10) t2=Test()
11) t3=Test()
12) t1.m1()
Output
Constructor exeuction...
Constructor exeuction...
Constructor exeuction...
Method execution...
Program:
1) class Student:
2)
3) ''''' This is student class with required data'''
4) def init (self,x,y,z):
5) self.name=x
6) self.rollno=y
7) self.marks=z
8)
9) def display(self):
10) print("Student Name:{}\nRollno:{} \nMarks:{}".format(self.name,self.rollno,self
.marks))
11)
12) s1=Student("Durga",101,80)
13) s1.display()
14) s2=Student("Sunny",102,100)
15) s2.display()
Output
Student Name:Durga
Rollno:101
Marks:80
Types of Variables:
Inside Python class 3 types of variables are allowed.
1)Instance Variables:
If the value of a variable is varied from object to object, then such type of variables are
called instance variables.
For every object a separate copy of instance variables will be created.
1) class Employee:
2)
3) def init (self):
4) self.eno=100
5) self.ename='Durga'
1) class Test:
2)
3) def init (self):
4) self.a=10
5) self.b=20
6)
7) def m1(self):
8) self.c=30
9)
10) t=Test()
11) t.m1()
12) print(t. dict )
1) class Test:
2)
3) def init (self):
4) self.a=10
5) self.b=20
6) def m1(self):
7) self.c=30
8)
9) t=Test()
10) t.m1()
11) t.d=40
12) print(t. dict )
1) class Test:
2)
3) def init (self):
4) self.a=10
5) self.b=20
6) def display(self):
7) print(self.a)
8) print(self.b)
9)
10) t=Test()
11) t.display()
12) print(t.a,t.b)
Output
10
20
10 20
1) class Test:
2) def init (self):
3) self.a=10
4) self.b=20
5) self.c=30
6) self.d=40
7) def m1(self):
8) del self.d
9)
10) t=Test()
11) print(t. dict )
12) t.m1()
13) print(t. dict )
14) del t.c
15) print(t. dict )
Note: The instance variables which are deleted from one object,will not be deleted from
other objects.
1) class Test:
2) def init (self):
3) self.a=10
4) self.b=20
5) self.c=30
6) self.d=40
7)
8) t1=Test()
9) t2=Test()
10) del t1.a
11) print(t1. dict )
12) print(t2. dict )
Output
{'b': 20, 'c': 30, 'd': 40}
{'a': 10, 'b': 20, 'c': 30, 'd': 40}
If we change the values of instance variables of one object then those changes won't be
reflected to the remaining objects, because for every object we are separate copy of
instance variables are available.
1) class Test:
2) def init (self):
3) self.a=10
4) self.b=20
5)
6) t1=Test()
7) t1.a=888
8) t1.b=999
9) t2=Test()
10) print('t1:',t1.a,t1.b)
11) print('t2:',t2.a,t2.b)
Output
t1: 888 999
t2: 10 20
1) class Test:
2) x=10
3) def init (self):
4) self.y=20
5)
6) t1=Test()
7) t2=Test()
8) print('t1:',t1.x,t1.y)
9) print('t2:',t2.x,t2.y)
10) Test.x=888
11) t1.y=999
12) print('t1:',t1.x,t1.y)
13) print('t2:',t2.x,t2.y)
Output
t1: 10 20
t2: 10 20
t1: 888 999
t2: 888 20
1) class Test:
2) a=10
3) def init (self):
4) print(self.a)
5) print(Test.a)
6) def m1(self):
7) print(self.a)
8) print(Test.a)
9) @classmethod
10) def m2(cls):
11) print(cls.a)
12) print(Test.a)
1) class Test:
2) a=777
3) @classmethod
4) def m1(cls):
5) cls.a=888
6) @staticmethod
7) def m2():
8) Test.a=999
9) print(Test.a)
10) Test.m1()
11) print(Test.a)
12) Test.m2()
13) print(Test.a)
Output
777
888
999
*****
If we change the Value of Static Variable by using either self OR
Object Reference Variable:
If we change the value of static variable by using either self or object reference variable,
then the value of static variable won't be changed, just a new instance variable with that
name will be added to that particular object.
1) class Test:
2) a=10
3) def m1(self):
4) self.a=888
Output
10
888
1) class Test:
2) x=10
3) def init (self):
4) self.y=20
5)
6) t1=Test()
7) t2=Test()
8) print('t1:',t1.x,t1.y)
9) print('t2:',t2.x,t2.y)
10) t1.x=888
11) t1.y=999
12) print('t1:',t1.x,t1.y)
13) print('t2:',t2.x,t2.y)
Output
t1: 10 20
t2: 10 20
t1: 888 999
t2: 10 20
1) class Test:
2) a=10
3) def init (self):
4) self.b=20
5) t1=Test()
6) t2=Test()
7) Test.a=888
8) t1.b=999
9) print(t1.a,t1.b)
10) print(t2.a,t2.b)
Output
888 999
888 20
1) class Test:
2) a=10
3) def init (self):
4) self.b=20
5) @classmethod
6) def m1(cls):
7) cls.a=888
8) cls.b=999
9)
10) t1=Test()
11) t2=Test()
12) t1.m1()
13) print(t1.a,t1.b)
14) print(t2.a,t2.b)
15) print(Test.a,Test.b)
Output
888 20
888 20
888 999
1) class Test:
2) a=10
3) @classmethod
4) def m1(cls):
5) del cls.a
6) Test.m1()
7) print(Test. dict )
Example:
1) class Test:
2) a=10
3) def init (self):
4) Test.b=20
5) del Test.a
6) def m1(self):
7) Test.c=30
8) del Test.b
9) @classmethod
10) def m2(cls):
11) cls.d=40
12) del Test.c
13) @staticmethod
14) def m3():
15) Test.e=50
16) del Test.d
17) print(Test. dict )
18) t=Test()
19) print(Test. dict )
20) t.m1()
21) print(Test. dict )
22) Test.m2()
23) print(Test. dict )
24) Test.m3()
25) print(Test. dict )
26) Test.f=60
27) print(Test. dict )
****Note:
⚽ By using object reference variable/self we can read static variables, but we cannot
modify or delete.
⚽ If we are trying to modify, then a new instance variable will be added to that
particular object.
⚽ t1.a = 70
⚽ If we are trying to delete then we will get error.
Example:
1) class Test:
2) a=10
3)
4) t1=Test()
5) del t1.a ===>AttributeError: a
We can modify or delete static variables only by using classname or cls variable.
1) import sys
2) class Customer:
3) ''''' Customer class with bank operations.. '''
4) bankname='DURGABANK'
5) def init (self,name,balance=0.0):
6) self.name=name
7) self.balance=balance
8) def deposit(self,amt):
9) self.balance=self.balance+amt
10) print('Balance after deposit:',self.balance)
11) def withdraw(self,amt):
12) if amt>self.balance:
13) print('Insufficient Funds..cannot perform this operation')
14) sys.exit()
15) self.balance=self.balance-amt
16) print('Balance after withdraw:',self.balance)
17)
18) print('Welcome to',Customer.bankname)
19) name=input('Enter Your Name:')
20) c=Customer(name)
21) while True:
22) print('d-Deposit \nw-Withdraw \ne-exit')
23) option=input('Choose your option:')
Output: D:\
durga_classes>py test.py
Welcome to DURGABANK
Enter Your Name:Durga
d-Deposit
w-Withdraw
e-exit
3)Local Variables:
⚽ Sometimes to meet temporary requirements of programmer,we can declare variables
inside a method directly,such type of variables are called local variable or temporary
variables.
⚽ Local variables will be created at the time of method execution and destroyed once
method completes.
⚽ Local variables of a method cannot be accessed from outside of method.
1) class Test:
2) def m1(self):
3) a=1000
4) print(a)
5) def m2(self):
6) b=2000
7) print(b)
8) t=Test()
9) t.m1()
10) t.m2()
Output
1000
2000
1) class Test:
2) def m1(self):
3) a=1000
4) print(a)
5) def m2(self):
6) b=2000
7) print(a) #NameError: name 'a' is not defined
8) print(b)
9) t=Test()
10) t.m1()
11) t.m2()
1) Instance Methods
2) Class Methods
3) Static Methods
1)Instance Methods:
⚽ Inside method implementation if we are using instance variables then such type of
methods are called instance methods.
⚽ 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.
⚽ Within the class we can call instance method by using self variable and from outside of
the class we can call by using object reference.
1) class Student:
2) def init (self,name,marks):
3) self.name=name
4) self.marks=marks
5) def display(self):
6) print('Hi',self.name)
7) print('Your Marks are:',self.marks)
8) def grade(self):
9) if self.marks>=60:
10) print('You got First Grade')
11) elif self.marks>=50:
12) print('Yout got Second Grade')
13) elif self.marks>=35:
14) print('You got Third Grade')
15) else:
16) print('You are Failed')
17) n=int(input('Enter number of students:'))
18) for i in range(n):
19) name=input('Enter Name:')
20) marks=int(input('Enter Marks:'))
21) s= Student(name,marks)
22) s.display()
23) s.grade()
24) print()
Ouput: D:\
durga_classes>py test.py
Enter number of students:2
Enter Name:Ravi
Enter Marks:12
Hi Ravi
Your Marks are: 12
You are Failed
Setter Method:
setter methods can be used to set values to the instance variables. setter methods also
known as mutator methods.
Syntax:
def setVariable(self,variable):
self.variable=variable
Example:
def setName(self,name):
self.name=name
Getter Method:
Getter methods can be used to get values of the instance variables. Getter methods also
known as accessor methods.
Syntax:
def getVariable(self):
return self.variable
Example:
def getName(self):
return self.name
1) class Student:
2) def setName(self,name):
3) self.name=name
4)
Output:
D:\python_classes>py test.py
Enter number of students:2
Enter Name:Durga
Enter Marks:100
Hi Durga
Your Marks are: 100
Enter Name:Ravi
Enter Marks:80
Hi Ravi
Your Marks are: 80
2)Class Methods:
⚽ Inside method implementation if we are using only class variables (static variables),
then such type of methods we should declare as class method.
⚽ We can declare class method explicitly by using @classmethod decorator.
⚽ For class method we should provide cls variable at the time of declaration
⚽ We can call classmethod by using classname or object reference variable.
Output D:\
python_classes>py test.py
Dog walks with 4 lEgs...
Cat walks with 4 lEgs...
3)Static Methods:
⚽ In general these methods are general utility methods.
⚽ Inside these methods we won't use any instance or class variables.
⚽ Here we won't provide self or cls arguments at the time of declaration.
⚽ We can declare static method explicitly by using @staticmethod decorator
⚽ We can access static methods by using classname or object reference
1) class DurgaMath:
2)
3) @staticmethod
4) def add(x,y):
5) print('The Sum:',x+y)
6)
Output
The Sum: 30
The Product: 200
The average: 15.0
Note:
In general we can use only instance and static methods.Inside static method we can
access class level variables by using class name.
Class methods are most rarely used methods in python.
1) class Employee:
2) def init (self,eno,ename,esal):
3) self.eno=eno
4) self.ename=ename
5) self.esal=esal
6) def display(self):
7) print('Employee Number:',self.eno)
8) print('Employee Name:',self.ename)
9) print('Employee Salary:',self.esal)
10) class Test:
11) def modify(emp):
12) emp.esal=emp.esal+10000
13) emp.display()
14) e=Employee(100,'Durga',10000)
15 Test.modify(e)
)
In the above application, Employee class members are available to Test class.
Inner Classes
Sometimes we can declare a class inside another class, such type of classes are called
inner classes.
Without existing one type of object if there is no chance of existing another type of object,
then we should go for inner classes.
Example: Without existing Car object there is no chance of existing Engine object.
Hence Engine class should be part of Car class.
class Car:
.....
class Engine:
......
class University:
.....
class Department:
......
Example: Without existing Human there is no chance of existin Head. Hence Head
should be part of Human.
class Human:
class Head:
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.
1) class Outer:
2) def init (self):
3) print("outer class object creation")
4) class Inner:
5) def init (self):
6) print("inner class object creation")
7) def m1(self):
8) print("inner class method")
9) o=Outer()
10) i=o.Inner()
11) i.m1()
Output
outer class object creation
inner class object creation
inner class method
Note: The following are various possible syntaxes for calling inner class method
1) o = Outer()
i = o.Inner()
i.m1()
2) i = Outer().Inner()
i.m1()
3) Outer().Inner().m1()
Demo Program-2:
1) class Person:
2) def init (self):
3) self.name='durga'
4) self.db=self.Dob()
5) def display(self):
6) print('Name:',self.name)
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))
Output
Name: durga
Dob=10/5/1947
Demo Program-3:
Inside a class we can declare any number of inner classes.
1) class Human:
2)
3) def init (self):
4) self.name = 'Sunny'
5) self.head = self.Head()
6) self.brain = self.Brain()
7) def display(self):
8) print("Hello..",self.name)
9)
10) class Head:
11) def talk(self):
12) print('Talking...')
13)
14) class Brain:
15) def think(self):
16) print('Thinking...')
17)
18) h=Human()
19) h.display()
20) h.head.talk()
21) h.brain.think()
Output
Hello.. Sunny
Talking...
Thinking...
⚽ 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
with memory problems is very less. This assistant is nothing but Garbage Collector.
⚽ Hence the main objective of Garbage Collector is to destroy useless objects.
⚽ If an object does not have any reference variable then that object eligible for Garbage
Collection.
1) import gc
2) print(gc.isenabled())
3) gc.disable()
4) print(gc.isenabled())
5) gc.enable()
6) print(gc.isenabled())
Output
True
False
True
Note: The job of destructor is not to destroy object and it is just to perform clean up
activities.
1) import time
2) class Test:
3) def init (self):
4) print("Object Initialization...")
5) def del (self):
6) print("Fulfilling Last Wish and performing clean up activities...")
7)
8) t1=Test()
9) t1=None
10) time.sleep(5)
11) print("End of application")
Output
Object Initialization...
Fulfilling Last Wish and performing clean up activities...
End of application
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 time
2) class Test:
3) def init (self):
4) print("Constructor Execution...")
5) def del (self):
6) print("Destructor Execution...")
7)
8) t1=Test()
9) t2=t1
10) t3=t2
11) del t1
12) time.sleep(5)
13) print("object not yet destroyed after deleting t1")
14) del t2
1) import time
2) class Test:
3) def init (self):
4) print("Constructor Execution...")
5) def del (self):
6) print("Destructor Execution...")
7)
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...
Destructor Execution...
End of application
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.
Inheritance
Has-A Relationship
IS-A Relationship
IS-A vs HAS-A Relationship
Composition vs Aggregation
Types of Inheritance
Single Inheritance
Multi Level Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
Cyclic Inheritance
Demo Program-1:
1) class Engine:
2) a=10
3) def init (self):
4) self.b=20
5) def m1(self):
Output:
Car using Engine Class Functionality
10
20
Engine Specific Functionality
Demo Program-2:
1) class Car:
2) def init (self,name,model,color):
3) self.name=name
4) self.model=model
5) self.color=color
6) def getinfo(self):
7) print("Car Name:{} , Model:{} and Color:{}".format(self.name,self.model,self.c
olor))
8)
9) class Employee:
10) def init (self,ename,eno,car):
11) self.ename=ename
12) self.eno=eno
13) self.car=car
14) def empinfo(self):
15) print("Employee Name:",self.ename)
16) print("Employee Number:",self.eno)
17) print("Employee Car Info:")
18) self.car.getinfo()
19) c=Car("Innova","2.5V","Grey")
20) e=Employee('Durga',10000,c)
21 e.empinfo()
)
In the above program Employee class Has-A Car reference and hence Employee class can
access all members of Car class.
Demo Program-3:
1) class X:
2) a=10
3) def init (self):
4) self.b=20
5) def m1(self):
6) print("m1 method of X class")
7)
8) class Y:
9) c=30
10) def init (self):
11) self.d=40
12) def m2(self):
13) print("m2 method of Y class")
14)
15) def m3(self):
16) x1=X()
17) print(x1.a)
18) print(x1.b)
19) x1.m1()
20) print(Y.c)
21) print(self.d)
22) self.m2()
23) print("m3 method of Y class")
24) y1=Y()
25 y1.m3()
)
Output:
10
20
m1 method of X class
30
40
m2 method of Y class
m3 method of Y class
1) class P:
2) a=10
3) def init (self):
4) self.b=10
5) def m1(self):
6) print('Parent instance method')
7) @classmethod
8) def m2(cls):
9) print('Parent class method')
10) @staticmethod
11) def m3():
12) print('Parent static method')
13)
14) class C(P):
15) pass
16)
17) c=C()
18) print(c.a)
19) print(c.b)
20) c.m1()
21) c.m2()
22) c.m3()
Output:
10
10
Parent instance method
Parent class method
Parent static method
1) class P:
2) 10 methods
3) class C(P):
4) 5 methods
Note: What ever members present in Parent class are by default available to the child
class through inheritance.
1) class P:
2) def m1(self):
3) print("Parent class method")
4) class C(P):
5) def m2(self):
6) print("Child class method")
7)
8) c=C();
9) c.m1()
10) c.m2()
Output:
Parent class method
Child class method
What ever methods present in Parent class are automatically available to the child class
and hence on the child class reference we can call both parent class methods and child
class methods.
1) class P:
2) a=10
3) def init (self):
4) self.b=20
5) class C(P):
6) c=30
7) def init (self):
8) super(). init___()===>Line-1
9) self.d=30
10)
11) c1=C()
12) print(c1.a,c1.b,c1.c,c1.d)
1) class Person:
2) def init (self,name,age):
3) self.name=name
4) self.age=age
5) def eatndrink(self):
6) print('Eat Biryani and Drink Beer')
7)
8) class Employee(Person):
9) def init (self,name,age,eno,esal):
10) super(). init (name,age)
11) self.eno=eno
12) self.esal=esal
13)
14) def work(self):
15) print("Coding Python is very easy just like drinking Chilled Beer")
16) def empinfo(self):
17) print("Employee Name:",self.name)
18) print("Employee Age:",self.age)
19) print("Employee Number:",self.eno)
20) print("Employee Salary:",self.esal)
21)
22) e=Employee('Durga', 48, 100, 10000)
23) e.eatndrink()
24) e.work()
25) e.empinfo()
Output:
Eat Biryani and Drink Beer
Coding Python is very easy just like drinking Chilled Beer
Employee Name: Durga
Employee Age: 48
Employee Number: 100
Employee Salary: 10000
IS - A
HAS - A
Employee Car
1) class Car:
2) def init (self,name,model,color):
3) self.name=name
4) self.model=model
5) self.color=color
6) def getinfo(self):
7) print("\tCar Name:{} \n\t Model:{} \n\t Color:{}".format(self.name,self.model,
self.color))
8)
9) class Person:
10) def init (self,name,age):
11) self.name=name
12) self.age=age
13) def eatndrink(self):
14) print('Eat Biryani and Drink Beer')
15)
16) class Employee(Person):
17) def init (self,name,age,eno,esal,car):
18) super(). init (name,age)
19) self.eno=eno
20) self.esal=esal
21) self.car=car
22) def work(self):
23) print("Coding Python is very easy just like drinking Chilled Beer")
24) def empinfo(self):
25) print("Employee Name:",self.name)
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")
33) e=Employee('Durga',48,100,10000,c)
34) e.eatndrink()
Output:
Eat Biryani and Drink Beer
Coding Python is very easy just like drinking Chilled Beer
Employee Name: Durga
Employee Age: 48
Employee Number: 100
Employee Salary: 10000
Employee Car Info:
Car Name:Innova
Model:2.5V
Color:Grey
In the above example Employee class extends Person class functionality but just uses Car
class functionality.
Composition vs Aggregation:
Composition:
Without existing container object if there is no chance of existing contained object then
the container and contained objects are strongly associated and that strong association is
nothing but Composition.
Eg: University contains several Departments and without existing university object there
is no chance of existing Department object. Hence University and Department objects are
strongly associated and this strong association is nothing but Composition.
Department Object
(Contained Object)
University Object
(Container Object)
Eg: Department contains several Professors. Without existing Department still there may
be a chance of existing Professor. Hence Department and Professor Objects are weakly
associated, which is nothing but Aggregation.
(Contained Object)
Professor Object
x
x
: :
: :
: :
x
Department Object
(Container Object)
Coding Example:
1) class Student:
2) collegeName='DURGASOFT'
3) def init (self,name):
4) self.name=name
5) print(Student.collegeName)
6) s=Student('Durga')
7) print(s.name)
Output:
DURGASOFT
Durga
In the above example without existing Student object there is no chance of existing his
name. Hence Student Object and his name are strongly associated which is nothing
but Composition.
But without existing Student object there may be a chance of existing collegeName. Hence
Student object and collegeName are weakly associated which is nothing but Aggregation.
Note: Whenever we are creating child class object then child class constructor will be
executed. If the child class does not contain constructor then parent class constructor will
be executed, but parent object won't be created.
1) class P:
2) def init (self):
3) print(id(self))
4) class C(P):
5) pass
6) c=C()
7) print(id(c))
Output:
6207088
6207088
1) class Person:
2) def init (self,name,age):
3) self.name=name
4) self.age=age
5) class Student(Person):
6) def init (self,name,age,rollno,marks):
7) super(). init (name,age)
8) self.rollno=rollno
9) self.marks=marks
10) def str (self):
11) return 'Name={}\nAge={}\nRollno={}\nMarks={}'.format(self.name,self.age,sel
f.rollno,self.marks)
12) s1=Student('durga',48,101,90)
13) print(s1)
Output:
Name=durga
Age=48
Rollno=101
Marks=90
Note: In the above example when ever we are creating child class object both parent and
child class constructors got executed to perform initialization of child object.
1) class P:
2) def m1(self):
3) print("Parent Method")
4) class C(P):
5) def m2(self):
6) print("Child Method")
7) c=C()
8) c.m1()
9) c.m2()
Output:
Parent Method
Child Method
Single Inheritance
1) class P:
2) def m1(self):
3) print("Parent Method")
4) class C(P):
5) def m2(self):
6) print("Child Method")
7) class CC(C):
8) def m3(self):
9) print("Sub Child Method")
10) c=CC()
Output:
Parent Method
Child Method
Sub Child Method
CC
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
C1 C2
Hierarchical
Inheritance
1) class P:
2) def m1(self):
3) print("Parent Method")
4) class C1(P):
Output:
Parent Method
Child1 Method
Parent Method
Child2 Method
4)Multiple Inheritance:
The concept of inheriting the properties from multiple classes into a single class at a
time, is known as multiple inheritance.
P1 P2
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")
Output:
Parent1 Method
Parent2 Method
Child2 Method
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.
1) class P1:
2) def m1(self):
3) print("Parent1 Method")
4) class P2:
5) def m1(self):
6) print("Parent2 Method")
7) class C(P1,P2):
8) def m2(self):
9) print("Child Method")
10) c=C()
11) c.m1()
12) c.m2()
Output:
Parent1 Method
Child Method
A B C
G H
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
really not required.
Eg - 1: class A(A):pass
NameError: name 'A' is not defined
Eg - 2:
1) class A(B):
2) pass
3) class B(A):
4) pass
B C
D
mro(A) = A, object
mro(B) = B, A, object
mro(C) = C, A, object
mro(D) = D, B, C, A, object
test.py
1) class A:pass
2) class B(A):pass
3) class C(A):pass
4) class D(B,C):pass
5) print(A.mro())
6) print(B.mro())
7) print(C.mro())
8) print(D.mro())
Output:
[<class ' main .A'>, <class 'object'>]
[<class ' main .B'>, <class ' main .A'>, <class 'object'>]
[<class ' main .C'>, <class ' main .A'>, <class 'object'>]
[<class ' main .D'>, <class ' main .B'>, <class ' main .C'>, <class ' main .A'>,
<class 'object'>]
Object
A B C
X Y
mro(A)=A,object P
mro(B)=B,object
mro(C)=C,object
mro(X)=X,A,B,object
mro(Y)=Y,B,C,object
mro(P)=P,X,A,Y,B,C,object
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
Output:
[<class ' main .A'>, <class 'object'>]
[<class ' main .X'>, <class ' main .A'>, <class ' main .B'>, <class 'object'>]
[<class ' main .Y'>, <class ' main .B'>, <class ' main .C'>, <class 'object'>]
[<class ' main .P'>, <class ' main .X'>, <class ' main .A'>, <class ' main .Y'>,
<class ' main .B'>,
<class ' main .C'>, <class 'object'>]
test.py
1) class A:
2) def m1(self):
3) print('A class Method')
4) class B:
5) def m1(self):
6) print('B class Method')
7) class C:
8) def m1(self):
9) print('C class Method')
10) class X(A,B):
11) def m1(self):
12) print('X class Method')
13) class Y(B,C):
14) def m1(self):
15) print('Y class Method')
16) class P(X,Y,C):
17) def m1(self):
18) print('P class Method')
19) p=P()
20) p.m1()
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
contain then A class method will be considered and this process will be continued.
Object
D E F
B C
mro(o) = object
mro(D) = D,object
mro(E) = E,object
mro(F) = F,object
mro(B) = B,D,E,object
mro(C) = C,D,F,object
mro(A) = A+Merge(mro(B),mro(C),BC)
= A+Merge(BDEO,CDFO,BC)
= A+B+Merge(DEO,CDFO,C)
= A+B+C+Merge(DEO,DFO)
= A+B+C+D+Merge(EO,FO)
= A+B+C+D+E+Merge(O,FO)
= A+B+C+D+E+F+Merge(O,O)
= A+B+C+D+E+F+O
test.py
1) class D:pass
2) class E:pass
3) class F:pass
4) class B(D,E):pass
5) class C(D,F):pass
6) class A(B,C):pass
7) print(D.mro())
8) print(B.mro())
Output:
[<class ' main .D'>, <class 'object'>]
[<class ' main .B'>, <class ' main .D'>, <class ' main .E'>, <class 'object'>]
[<class ' main .C'>, <class ' main .D'>, <class ' main .F'>, <class 'object'>]
[<class ' main .A'>, <class ' main .B'>, <class ' main .C'>, <class ' main .D'>,
<class ' main .E'>,
<class ' main .F'>, <class 'object'>]
super() Method:
super() is a built-in method which is useful to call the super class constructors,variables
and methods from the child class.
Output:
Name: Durga
Age: 22
Roll No: 101
Marks: 90
Output:
10
Parent instance method
Parent class method
Parent static method
In the above example we are using super() to call various members of Parent class.
1) super(D, self).m1()
It will call m1() method of super class of D.
2) A.m1(self)
It will call A class m1() method
1) class A:
2) def m1(self):
3) print('A class Method')
4) class B(A):
5) def m1(self):
6) print('B class Method')
7) class C(B):
8) def m1(self):
9) print('C class Method')
10) class D(C):
11) def m1(self):
12) print('D class Method')
13) class E(D):
14) def m1(self):
15) A.m1(self)
16)
17) e=E()
18) e.m1()
1) class P:
2) a=10
3) def init (self):
4) self.b=20
5)
6) class C(P):
7) def m1(self):
Output:
10
20
AttributeError: 'super' object has no attribute 'b'
Case-2: From child class constructor and instance method, we can access parent class
instance method, static method and class method by using super()
1) class P:
2) def init (self):
3) print('Parent Constructor')
4) def m1(self):
5) print('Parent instance method')
6) @classmethod
7) def m2(cls):
8) print('Parent class method')
9) @staticmethod
10) def m3():
11) print('Parent static method')
12)
13) class C(P):
14) def init (self):
15) super(). init ()
16) super().m1()
17) super().m2()
18) super().m3()
19)
20) def m1(self):
21) super(). init ()
22) super().m1()
23) super().m2()
24) super().m3()
25)
26) c=C()
27) c.m1()
Case-3: From child class, class method we cannot access parent class instance methods
and constructors by using super() directly(but indirectly possible). But we can access
parent class static and class methods.
1) class P:
2) def init (self):
3) print('Parent Constructor')
4) def m1(self):
5) print('Parent instance method')
6) @classmethod
7) def m2(cls):
8) print('Parent class method')
9) @staticmethod
10) def m3():
11) print('Parent static method')
12)
13) class C(P):
14) @classmethod
15) def m1(cls):
16) #super(). init ()--->invalid
17) #super().m1()--->invalid
18) super().m2()
19) super().m3()
20)
21) C.m1()
Output:
Parent class method
Parent static method
1) class A:
2) def init (self):
3) print('Parent constructor')
4)
5) def m1(self):
6) print('Parent instance method')
7)
8) class B(A):
9) @classmethod
10) def m2(cls):
11) super(B,cls). init (cls)
12) super(B,cls).m1(cls)
13)
14) B.m2()
Output:
Parent constructor
Parent instance method
Case-4: In child class static method we are not allowed to use super() generally (But in
special way we can use)
1) class P:
2) def init (self):
3) print('Parent Constructor')
4) def m1(self):
5) print('Parent instance method')
6) @classmethod
7) def m2(cls):
8) print('Parent class method')
9) @staticmethod
10) def m3():
11) print('Parent static method')
12)
13) class C(P):
14) @staticmethod
15) def m1():
16) super().m1()-->invalid
17) super().m2()--->invalid
18) super().m3()--->invalid
19)
20) C.m1()
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
9) def m2():
10) super(B,B).m1()
11)
12) B.m2()
Eg1: Yourself is best example of polymorphism.In front of Your parents You will have
one type of behaviour and with friends another type of behaviour.Same person but
different behaviours at different places,which is nothing but polymorphism.
Eg4: The Same method with different implementations in Parent class and child classes.
(overriding)
2) Overloading
1) Operator Overloading
2) Method Overloading
3) Constructor Overloading
3) Overriding
1) Method Overriding
2) Constructor Overriding
def f1(obj):
obj.talk()
Output:
Quack..
Quack.. Moew
Moew .. Bow
Bow..
Myaah Myaah ..
The problem in this approach is if obj does not contain talk() method then we will get
AttributeError.
1) class Duck:
2) def talk(self):
3) print('Quack.. Quack..')
4)
5) class Dog:
6) def bark(self):
7) print('Bow Bow..')
8) def f1(obj):
9) obj.talk()
10)
11) d=Duck()
12) f1(d)
13)
Output:
D:\durga_classes>py test.py
Quack.. Quack..
Traceback (most recent call last):
File "test.py", line 22, in <module>
f1(d)
File "test.py", line 13, in f1
obj.talk()
AttributeError: 'Dog' object has no attribute 'talk'
2) Overloading
We can use same operator or methods for different purposes.
1)Operator Overloading:
We can use the same operator for multiple purposes, which is nothing but
operator overloading.
Python supports operator overloading.
D:\durga_classes>py test.py
Traceback (most recent call last):
File "test.py", line 7, in <module>
print(b1+b2)
TypeError: unsupported operand type(s) for +: 'Book' and 'Book'
⚽ We can overload + operator to work with Book objects also. i.e Python supports
Operator Overloading.
⚽ For every operator Magic Methods are available. To overload any operator we have to
override that Method in our class.
⚽ Internally + operator is implemented by using add () method.This method is called
magic method for + operator. We have to override this method in our class.
Output
10>20 = False
s1>s2= False
s1<s2= True
s1<=s2= True
s1>=s2= False
1) class Employee:
2) def init (self,name,salary):
3) self.name=name
4) self.salary=salary
5) def mul (self,other):
6) return self.salary*other.days
7)
2)Method Overloading:
If 2 methods having same name but different type of arguments then those methods
are said to be overloaded methods.
Eg: m1(int a)
m1(double d)
Demo Program:
1) class Test:
2) def m1(self):
3) print('no-arg method')
4) def m1(self,a):
5) print('one-arg method')
6) def m1(self,a,b):
7) print('two-arg method')
8)
9) t=Test()
10) #t.m1()
11) #t.m1(10)
12) t.m1(10,20)
Output
The Sum of 2 Numbers: 30
The Sum of 3 Numbers: 60
Please provide 2 or 3 arguments
3)Constructor Overloading:
⚽ Constructor overloading is not possible in Python.
⚽ If we define multiple constructors then the last constructor will be considered.
1) class Test:
2) def init (self):
3) print('No-Arg Constructor')
4)
Output
Constructor with 0|1|2|3 number of
arguments Constructor with 0|1|2|3 number
of arguments Constructor with 0|1|2|3
number of arguments Constructor with 0|1|2|
3 number of arguments
3) Overriding
Method Overriding
⚽ 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
implementation then child class is allowed to redefine that method in the child class
based on its requirement. This concept is called overriding.
⚽ Overriding concept applicable for both methods and constructors.
Output
Gold+Land+Cash+Power
Katrina Kaif
From Overriding method of child class,we can call parent class method also by using
super() method.
1) class P:
2) def property(self):
3) print('Gold+Land+Cash+Power')
Output
Gold+Land+Cash+Power
Appalamma
Katrina Kaif
From child class constuctor we can call parent class constructor by using super() method.
Output
Employee Name: Durga
Employee Age: 48
Employee Number: 872425
Employee Salary: 26000
Abstract Method:
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
1) class Test:
2) @abstractmethod
3) def m1(self):
4) pass
Eg:
Child classes are responsible to provide implemention for parent class abstract methods.
Abstract class:
Some times implementation of a class is not complete,such type of partially
implementation classes are called abstract classes. Every abstract class in Python should
be derived from ABC class which is present in abc module.
Case-1:
In the above code we can create object for Test class b'z it is concrete class and it does not
conatin any abstract method.
Case-2:
In the above code we can create object, even it is derived from ABC class,b'z it does not
contain any abstract method.
Case-3:
Case-4:
We can create object even class contains abstract method b'z we are not extending ABC
class.
Case-5:
Output: Hello
Conclusion: If a class contains atleast one abstract method and if we are extending ABC
class then instantiation is not possible.
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
any error.
Case-1:
Case-2:
TypeError: Can't instantiate abstract class Bus with abstract methods noofwheels
Note: If we are extending abstract class and does not override its abstract method then
child class is also abstract and instantiation is not possible.
Note: Abstract class can contain both abstract and non-abstract methods also.
D:\durga_classes>py test.py
Enter Database Name:Oracle
Connecting to Oracle Database...
Disconnecting to Oracle Database...
D:\durga_classes>py test.py
Enter Database Name:Sybase
Connecting to Sybase Database...
Disconnecting to Sybase Database...
Note: The inbuilt function globals()[str] converts the string 'str' into a class name and
returns the classname.
config.txt
EPSON
test.py
Output:
Printing from EPSON Printer...
This data has to print...
Printing completed on EPSON Printer...
Protected attributes can be accessed within the class anywhere but from outside of the
class only in child classes. We can specify an attribute as protected by prefexing with _
symbol.
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.
syntax: variablename=value
Eg: name='durga'
1) class Test:
2) x=10
3) _y=20
4)______z=30
5) def m1(self):
6) print(Test.x)
7) print(Test._y)
8) print(Test. z)
9)
10) t=Test()
11) t.m1()
12) print(Test.x)
13) print(Test._y)
14) print(Test. z)
Output:
10
20
30
10
20
Traceback (most recent call last):
File "test.py", line 14, in <module>
print(Test. z)
AttributeError: type object 'Test' has no attribute ' z'
1) class Test:
2) def init (self):
3) self____=10
4)
str () method:
Whenever we are printing any object reference internally str () method will be
called which is returns string in the following format
< main .classname object at 0x022144B0>
1) class Student:
2) def init (self,name,rollno):
3) self.name=name
4) self.rollno=rollno
5)
6) def str (self):
7) return 'This is Student with Name:{} and Rollno:{}'.format(self.name,self.rollno)
8)
9) s1=Student('Durga',101)
10) s2=Student('Ravi',102)
11) print(s1)
12) print(s2)
D:\durgaclasses>py test.py
2018-05-18 22:48:19.890888
Traceback (most recent call last):
File "test.py", line 5, in <module>
d=eval(s)#converting str object to datetime
File "<string>", line 1
2018-05-18 22:48:19.890888
^
SyntaxError: invalid token
1) import datetime
2) today=datetime.datetime.now()
3) s=repr(today)#converting datetime object to str
4) print(s)
5) d=eval(s)#converting str object to datetime
6) print(d)
Output:
datetime.datetime(2018, 5, 18, 22, 51, 10, 875838)
2018-05-18 22:51:10.875838
Output:
D:\durgaclasses>py test.py
Durga's Savings Account with Balance :10000
Account Balance: 15000
Sorry, Insufficient Funds
Durga's Savings Account with Balance :0
Ravi's Current Account with Balance :26000
Ravi's Current Account with Balance :-1000
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")
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.
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
Eg:
ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError
SleepingError
TyrePuncturedError
Exception handling does not mean repairing exception. We have to define alternative way to
continue rest of the program normally.
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.
try:
Read Data from Remote File locating at London.
except FileNotFoundError:
use local file and continue rest of the program normally
Q. What is an Exception?
Q. What is the purpose of Exception Handling?
Q. What is the meaning of Exception Handling?
D:\Python_classes>py test.py
Hello
Traceback (most recent call last):
File "test.py", line 2, in <module>
print(10/0)
ZeroDivisionError: division by zero
Overflow Permission
Error Error
TimeOut
Every Exception in Python is a class. Error
All exception classes are child classes of BaseException.i.e every exception class
extends BaseException either directly or indirectly. Hence BaseException acts as root
for Python Exception Hierarchy.
Most of the times being a programmer we have to concentrate Exception and its
child classes.
Without try-except:
1) print("stmt-1")
2) print(10/0)
3) print("stmt-3")
Output
stmt-1
ZeroDivisionError: division by zero
Abnormal termination/Non-Graceful Termination
With try-except:
1) print("stmt-1")
2) try:
3) print(10/0)
4) except ZeroDivisionError:
5) print(10/2)
6) print("stmt-3")
Output
stmt-1
5.0
stmt-3
Normal termination/Graceful Termination
Case-3: If an exception rose at stmt-2 and corresponding except block not matched
1, Abnormal Termination
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
code inside try block and length of the try block should be as less as possible.
2) In addition to try block, there may be a chance of raising exceptions inside except and
finally blocks also.
3) If any statement which is not part of try block raises an exception then it is always
abnormal termination.
1) print(10/0)
2) except ZeroDivisionError as msg:
3) print("exception raised and its description is:",msg)
Eg:
try:
-------
-------
-------
except ZeroDivisionError:
perform alternative arithmetic operations
If try with multiple except blocks available then based on raised exception the
corresponding except block will be executed.
1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except ZeroDivisionError :
6) print("Can't Divide with Zero")
7) except ValueError:
8) print("please provide int value only")
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: 2
5.0
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: 0
Can't Divide with Zero
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: ten
please provide int value only
If try with multiple except blocks available then the order of these except blocks is
important .Python interpreter will always consider from top to bottom until matched
except block identified.
1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except ArithmeticError :
6) print("ArithmeticError")
7) except ZeroDivisionError:
8) print("ZeroDivisionError")
D:\Python_classes>py test.py
Enter First Number: 10
except (Exception1,Exception2,exception3,..): OR
except (Exception1,Exception2,exception3,..) as msg
:
Parentheses are mandatory and this group of exceptions internally considered as tuple.
1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except (ZeroDivisionError,ValueError) as msg:
6) print("Plz Provide valid numbers only and problem is: ",msg)
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: 0
Plz Provide valid numbers only and problem is: division by zero
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: ten
Plz Provide valid numbers only and problem is: invalid literal for int() with b are 10: 'ten'
Syntax:
except:
statements
1) try:
2) x=int(input("Enter First Number: "))
3) y=int(input("Enter Second Number: "))
4) print(x/y)
5) except ZeroDivisionError:
6) print("ZeroDivisionError:Can't divide with zero")
7) except:
8) print("Default Except:Plz provide valid input only")
D:\Python_classes>py test.py
Enter First Number: 10
Enter Second Number: ten
Default Except:Plz provide valid input only
***Note: If try with multiple except blocks available then default except block should be
last, otherwise we will get SyntaxError.
1) try:
2) print(10/0)
3) except:
4) print("Default Except")
5) except ZeroDivisionError:
6) print("ZeroDivisionError")
finally Block:
☕ It is not recommended to maintain clean up code(Resource Deallocating Code or
Resource Releasing code) inside try block because there is no guarentee for the
execution of every statement inside try block always.
☕ It is not recommended to maintain clean up code inside except block, because if
there is no exception then except block won't be executed.
☕ Hence we required some place to maintain clean up code which should be executed
always irrespective of whether exception raised or not raised and whether exception
handled or not handled. Such type of best place is nothing but finally block.
☕ Hence the main purpose of finally block is to maintain clean up code.
try:
Risky Code
except:
Handling Code
The speciality of finally block is it will be executed always whether exception raised or not
raised and whether exception handled or not handled.
1) try:
2) print("try")
3) except:
4) print("except")
5) finally:
6) print("finally")
Output
try
finally
1) try:
2) print("try")
3) print(10/0)
4) except ZeroDivisionError:
5) print("except")
6) finally:
7) print("finally")
Output
try
except
finally
1) try:
2) print("try")
3) print(10/0)
4) except NameError:
5) print("except")
6) finally:
7) print("finally")
*** Note: There is only one situation where finally block won't be executed ie whenever
we are using os._exit(0) function.
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.
1) imports
2) try:
3) print("try")
4) os._exit(0)
5) except NameError:
6) print("except")
7) finally:
8) print("finally")
Output: try
Note:
os._exit(0)
Where 0 represents status code and it indicates normal termination
There are multiple status codes are possible.
Case-2: If an exception raised at stmt2 and the corresponding except block matched
1,4,5,6 Normal Termination
Case-4:If an exception raised at stmt4 then it is always abnormal termination but before
that finally block will be executed.
General Risky code we have to take inside outer try block and too much risky code we
have to take inside inner try block. Inside Inner try block if an exception raised then inner
except block is responsible to handle. If it is unable to handle then outer except block is
responsible to handle.
1) try:
2) print("outer try block")
3) try:
4) print("Inner try block")
5) print(10/0)
6) except ZeroDivisionError:
7) print("Inner except block")
8) finally:
9) print("Inner finally block")
Output
outer try block
Inner try block
Inner except block
Inner finally block
outer finally block
Case-2: If an exception raised at stmt-2 and the corresponding except block matched
1,10,11,12 Normal Termination
Case-3: If an exceptiion raised at stmt-2 and the corresponding except block not matched
1,11,Abnormal Termination
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
Case-8: If an exception raised at stmt-7 and corresponding except block not matched
1,2,3,.,.,.,8,11,Abnormal Termination
Case-10: If an exception raised at stmt-8 and corresponding except block not matched
1,2,3,.,.,.,.,11,Abnormal Termination
Case-12: If an exception raised at stmt-9 and corresponding except block not matched
1,2,3,.,.,.,.,8,11,Abnormal Termination
Note: If the control entered into try block then compulsary finally block will be executed.
If the control not entered into try block then finally block won't be executed.
try:
Risky Code
except:
will be executed if exception inside try
Eg:
try:
print("try")
print(10/0) 1
except:
print("except")
else:
print("else")
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
else
finally
If we are not commenting line-1 then else block won't be executed b'z there is exception
inside try block. In this case output is:
try
except
finally
except:
print("except")
21 try:
print("inner try")
√
except:
print("inner except block")
finally:
print("inner finally block")
try:
print("try")
22 except:
print("except")
√
finally:
Types of Exceptions:
In Python there are 2 types of exceptions are possible.
1) Predefined Exceptions
2) User Definded Exceptions
1)Predefined Exceptions:
Also known as inbuilt exceptions.
The exceptions which are raised automatically by Python virtual machine whenver a
particular event occurs are called pre defined exceptions.
Syntax:
class classname(predefined exception class name):
def init (self,arg):
self.msg=arg
1) class TooYoungException(Exception):
2) def init (self,arg):
3) self.msg=arg
1) class TooYoungException(Exception):
2) def init (self,arg):
3) self.msg=arg
4)
5) class TooOldException(Exception):
6) def init (self,arg):
7) self.msg=arg
8)
D:\Python_classes>py test.py
Enter Age:90
main .TooYoungException: Plz wait some more time you will get best match soon!!!
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
Types of Files:
There are 2 types of files
1) Text Files:
Usually we can use text files to store character data
Eg: abc.txt
2) Binary Files:
Usually we can use binary files to store binary data like images,video files, audio files
etc...
Opening a File:
Before performing any operation (like read or write) on the file,first we have to open
that file.For this we should use Python's inbuilt function open()
But at the time of open, we have to specify mode,which represents the purpose of
opening file.
f = open(filename, mode)
1) r open an existing file for read operation. The file pointer is positioned at the
beginning of the file.If the specified file does not exist then we will get
FileNotFoundError.This is default mode.
2) w open an existing file for write operation. If the file already contains some data
then it will be overridden. If the specified file is not already avaialble then this mode
will create that file.
3) a open an existing file for append operation. It won't override existing data.If the
specified file is not already avaialble then this mode will create a new file.
4) r+ To read and write data into the file. The previous data in the file will not be
deleted.The file pointer is placed at the beginning of the file.
5) w+ To write and read data. It will override existing data.
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.
Eg: rb,wb,ab,r+b,w+b,a+b,xb
f = open("abc.txt","w")
We are opening abc.txt file for writing data.
Closing a File:
After completing our operations on the file, it is highly recommended to close the file. For
this we have to use close() function.
f.close()
1) f=open("abc.txt",'w')
2) print("File Name: ",f.name)
3) print("File Mode: ",f.mode)
4) print("Is File Readable: ",f.readable())
5) print("Is File Writable: ",f.writable())
6) print("Is File Closed : ",f.closed)
7) f.close()
8) print("Is File Closed : ",f.closed)
Output D:\Python_classes>py
test.py File Name: abc.txt
File Mode: w
Is File Readable: False Is
File Writable: True Is
File Closed: False
Is File Closed: True
1) f=open("abcd.txt",'w')
2) f.write("Durga\n")
3) f.write("Software\n")
4) f.write("Solutions\n")
5) print("Data written to the file successfully")
6) f.close()
abcd.txt:
Durga
Software
Solutions
Note: In the above program, data present in the file will be overridden everytime if we
run the program. Instead of overriding if we want append operation then we should open
the file as follows.
f = open("abcd.txt","a")
Eg 2:
1) f=open("abcd.txt",'w')
2) list=["sunny\n","bunny\n","vinny\n","chinny"]
3) f.writelines(list)
4) print("List of lines written to the file successfully")
5) f.close()
abcd.txt:
sunny
bunny
vinny
chinny
Note: While writing data by using write() methods, compulsory we have to provide line seperator(\
n), otherwise total data should be written to a single line.
1) f=open("abc.txt",'r')
2) data=f.read()
3) print(data)
4) f.close()
Output
sunny
bunny
chinny
vinny
1) f=open("abc.txt",'r')
2) data=f.read(10)
3) print(data)
4) f.close()
Output
sunny
bunn
1) f=open("abc.txt",'r')
2) line1=f.readline()
3) print(line1,end='')
4) line2=f.readline()
5) print(line2,end='')
6) line3=f.readline()
7) print(line3,end='')
8) f.close()
1) f=open("abc.txt",'r')
2) lines=f.readlines()
3) for line in lines:
4) print(line,end='')
5) f.close()
Output
sunny
bunny
chinny
vinny
Eg 5:
1) f=open("abc.txt","r")
2) print(f.read(3))
3) print(f.readline())
4) print(f.read(4))
5) print("Remaining data")
6) print(f.read())
Output
sun
ny
bunn
Remaining
data y
chinny
vinny
Output
Is File Closed: False Is
File Closed: True
1) f=open("abc.txt","r")
2) print(f.tell())
3) print(f.read(2))
4) print(f.tell())
5) print(f.read(3))
6) print(f.tell())
abc.txt:
sunny
bunny
chinny
vinny
Output:
0
su 2
nny 5
seek():
We can use seek() method to move cursor (file pointer) to specified location. [Can
you please seek the cursor to a particular location]
f.seek(offset, fromwhere) offset represents the number of positions
Note: Python 2 supports all 3 values but Python 3 supports only zero.
Output
All Students are STUPIDS
The Current Cursor Position: 24
The Current Cursor Position: 17
Data After Modification:
All Students are GEMS!!!
1) import os,sys
2) fname=input("Enter File Name: ")
3) if os.path.isfile(fname):
4) print("File exists:",fname)
5) f=open(fname,"r")
6) else:
Output D:\
Python_classes>py test.py
Enter File Name: durga.txt
File does not exist: durga.txt
D:\Python_classes>py test.py
Enter File Name: abc.txt
File exists: abc.txt
The content of file is:
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
All Students are GEMS!!!
Note:
sys.exit(0) To exit system without executing rest of the program.
argument represents status code. 0 means normal termination and it is the default value.
Output D:\
Python_classes>py test.py
Enter File Name: durga.txt
File does not exist: durga.txt
D:\Python_classes>py test.py
Enter File Name: abc.txt
File exists: abc.txt
The number of Lines: 6
The number of Words: 24
The number of Characters: 149
abc.txt
All Students are
GEMS!!! All Students
are GEMS!!! All
Students are GEMS!!!
All Students are
GEMS!!! All Students
are GEMS!!! All
Students are GEMS!!!
1) f1=open("rossum.jpg","rb")
2) f2=open("newpic.jpg","wb")
3) bytes=f1.read()
4) f2.write(bytes)
5) print("New Image is available with the name: newpic.jpg")
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
attribute.
Output
D:\Python_classes>py test.py
To perform zip and unzip operations, Python contains one in-bulit module zip file.
This module contains a class: ZipFile
Once we create ZipFile object,we can add files by using write() method.
f.write(filename)
ZIP_STORED represents unzip operation. This is default value and hence we are not
required to specify.
Once we created ZipFile object for unzip operation, we can get all file names present in
that zip file by using namelist() method.
names = f.namelist()
import os
os.mkdir("mysub/mysub2")
print("mysub2 created inside mysub")
1) import os
2) print(os.listdir("."))
Output
D:\Python_classes>py test.py
['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 ']
The above program display contents of current working directory but not contents
of sub directories.
If we want the contents of a directory including sub directories then we should go
for walk() function.
Eg: To display all contents of Current working directory including sub directories:
1) import os
2) for dirpath,dirnames,filenames in os.walk('.'):
3) print("Current Directory Path:",dirpath)
4) print("Directories:",dirnames)
5) print("Files:",filenames)
6) print()
Output
Current Directory Path: .
Directories: ['com', 'newdir', 'pack1', ' pycache ']
Files: ['abc.txt', 'abcd.txt', 'demo.py', 'durgamath.py', 'emp.csv', 'file1.txt', 'file2.txt', 'file3.
txt', 'files.zip', 'log.txt', 'module1.py', 'mylog.txt', 'newpic.jpg', 'rossum.jpg', 'test.py']
Note: To display contents of particular directory, we have to provide that directory name as
argument to walk() function.
os.walk("directoryname")
os.system("commad string")
The argument is any command which is executing from DOS.
Eg:
import os os.system("dir
*.py") os.system("py
abc.py")
Note: st_atime, st_mtime and st_ctime returns the time as number of milli seconds since
Jan 1st 1970, 12:00 AM. By using datetime module from timestamp() function, we can get
exact date and time.
Output
os.stat_result(st_mode=33206, st_ino=844424930132788, st_dev=2657980798, st_nlin
k=1, st_uid=0, st_gid=0, st_size=22410, st_atime=1505451446, st_mtime=1505538999
, st_ctime=1505451446)
pickling
pickle.dump
eno: 100 (e1, f)
ename: Durga
esal: 10000
eaddr: HYD
e1 eno: 100
ename: Durga
esal: 10000
eaddr: HYD
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)
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.
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.
Note: threading module contains function current_thread() which returns the current
executing Thread object. On this object if we call getName() method then we will get
current executing thread name.
If multiple threads present in our program, then we cannot expect execution order and
hence we cannot expect exact output for the multi threaded programs. B'z of this we
cannot provide exact output for the above program.It is varied from machine to machine
and run to run.
Note: Thread is a pre defined class present in threading module which can be used to create
our own Threads.
We can get and set name of thread by using the following Thread class methods.
t.getName() Returns Name of Thread
t.setName(newName) To set our own name
Note: Every Thread has implicit variable "name" to represent name of Thread.
Output
MainThread
Pawan Kalyan
Pawan Kalyan
Output:
Child Thread
Main Thread Identification Number: 2492
Child Thread Identification Number: 2768
active_count():
This function returns the number of active threads currently running.
Output:
D:\python_classes>py test.py
The Number of active Threads: 1
ChildThread1 ...started
ChildThread2 ...started
ChildThread3 ...started
The Number of active Threads: 4
enumerate() Function:
This function returns a list of all active threads currently running.
Output: D:\
python_classes>py test.py
ChildThread1 ...started
ChildThread2 ...started
ChildThread3 ...started
Thread Name: MainThread
Thread Name: ChildThread1
Thread Name: ChildThread2
Thread Name: ChildThread3
ChildThread1 ...ended
ChildThread2 ...ended
ChildThread3 ...ended
Thread Name: MainThread
Output:
D:\python_classes>py test.py
ChildThread1 ...started
ChildThread2 ...started
ChildThread1 is Alive : True
ChildThread2 is Alive : True
ChildThread1 ...ended
ChildThread2 ...ended
ChildThread1 is Alive : False
ChildThread2 is Alive : False
join() Method:
If a thread wants to wait until completing some other thread then we should go for join()
method.
In the above example Main Thread waited until completing child thread. In this case
output is:
Seetha Thread
Seetha Thread
Seetha Thread
Seetha Thread
Seetha Thread
Seetha Thread
Seetha Thread
Seetha Thread
Seetha Thread
Seetha Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
t.join(seconds)
In this case thread will wait only specified amount of time.
Output
Seetha Thread
Seetha Thread
Seetha Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
Rama Thread
Seetha Thread
Seetha Thread
Seetha Thread
Seetha Thread
Seetha Thread
Seetha Thread
Seetha Thread
Daemon Threads:
The threads which are running in the background are called Daemon Threads.
The main objective of Daemon Threads is to provide support for Non
Daemon Threads( like main thread)
Eg: Garbage Collector
Whenever Main Thread runs with low memory, immediately PVM runs Garbage
Collector to destroy useless objects and to provide free memory,so that Main
Thread can continue its execution without having any memory problems.
We can check whether thread is Daemon or not by using t.isDaemon() method
of Thread class or by using daemon property.
Default Nature:
By default Main Thread is always non-daemon.But for the remaining threads Daemon nature
will be inherited from parent to child.i.e if the Parent Thread is Daemon then child thread
is also Daemon and if the Parent Thread is Non Daemon then ChildThread is also Non
Daemon.
Note: Main Thread is always Non-Daemon and we cannot change its Daemon Nature b'z it
is already started at the beginning only.
Whenever the last Non-Daemon Thread terminates automatically all Daemon Threads will be
terminated.
Lazy
Thread
Lazy
Thread
Lazy Thread
End Of Main
Thread Lazy Thread
Lazy
Thread
Lazy
Thread
Lazy
Thread
Lazy
Thread
Lazy
Thread
Lazy Thread
If we are not commenting Line-1 then Main Thread is Non-Daemon and Child Thread is
Daemon. Hence whenever MainThread terminates automatically child thread will be
terminated. In this case output is
Lazy
Thread
Lazy
Thread
Lazy Thread
End of Main Thread
Synchronization:
If multiple threads are executing simultaneously then there may be a chance of data
inconsistency problems.
We are getting irregular output b'z both threads are executing simultaneously wish()
function.
To overcome this problem we should go for synchronization.
In synchronization the threads will be executed one by one so that we can
overcome data inconsistency problems.
Synchronization means at a time only one Thread
Note: To call release() method compulsory thread should be owner of that lock.i.e
thread should has the lock already,otherwise we will get Runtime Exception saying
RuntimeError: release unlocked lock.
If we are commenting line-1 then we will get RuntimeError: release unlocked lock
Output
D:\python_classes>py test.py
Main Thread trying to acquire
Lock
Main Thread trying to acquire Lock Again
--
In the above Program main thread will be blocked b'z it is trying to acquire the lock second
time.
Note: To kill the blocking thread from windows command prompt we have to use
ctrl+break. Here ctrl+C won't work.
If the Thread calls recursive functions or nested access to resources,then the thread may
trying to acquire the same lock again and again,which may block our thread.
Reentrant facility is available only for owner thread but not for other threads.
In this case Main Thread won't be Locked b'z thread can acquire the lock any number of
times.
This RLock keeps track of recursion level and hence for every acquire() call compulsory
release() call should be available. i.e the number of acquire() calls and release() calls
should be matched then only lock will be released.
Eg:
l=RLock()
l.acquire()
l.acquire()
l.release()
l.release()
Note:
1) Only owner thread can acquire the lock multiple times
2) The number of acquire() calls and release() calls should be matched.
Output:
The Factorial of 5 is: 120
The Factorial of 9 is: 362880
In the above program instead of RLock if we use normal Lock then the thread will be
blocked.
Case-1: s = Semaphore()
In this case counter value is 1 and at a time only one thread is allowed to access. It is
exactly same as Lock concept.
Case-2: s = Semaphore(3)
In this case Semaphore object can be accessed by 3 threads at a time.The remaining
threads have to wait until releasing the semaphore.
In the above program at a time 2 threads are allowed to access semaphore and hence 2
threads are allowed to execute wish() function.
☕ 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() calls should not exceed the number of acquire() calls,otherwise we will get
ValueError: Semaphore released too many times
Pseudo Code:
event = threading.Event()
#consumer thread has to wait until event is set
event.wait()
#producer thread can set or clear event
event.set()
event.clear()
Output:
Consumer thread is waiting for updation
Producer thread producing items
Producer thread giving notification by setting event
Consumer thread got notification and consuming items
Demo Program-2:
In the above program driver thread has to wait until Trafficpolice thread sets event.ie until
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
thread has to wait.
Methods of Condition:
1) acquire() To acquire Condition object before producing or consuming items.i.e
thread acquiring internal lock.
2) release() To release Condition object after producing or consuming items. i.e thread
releases internal lock
#Producer Thread
...generate item..
condition.acquire()
...add item to the resource...
condition.notify()#signal that a new item is available(notifyAll())
condition.release()
The Consumer must acquire the Condition and then it can consume items from the resource
#Consumer Thread
condition.acquire()
condition.wait()
consume item
condition.release()
Demo Program-1:
Demo Program-2:
Output
Consumer waiting for updation
Producer Producing Item: 49
Producer giving Notification
Consumer consumed the item 49
.....
Producer Thread uses put() method to insert data in the queue. Internally this method has
logic to acquire the lock before inserting data into queue. After inserting data lock will be
released automatically.
put() method also checks whether the queue is full or not and if queue is full then the
Producer thread will entered in to waiting state by calling wait() method internally.
Consumer Thread uses get() method to remove and get data from the queue. Internally
this method has logic to acquire the lock before removing data from the queue.Once
removal completed then the lock will be released automatically.
If the queue is empty then consumer thread will entered into waiting state by calling
wait() method internally.Once queue updated with data then the thread will be notified
automatically.
Note: The Queue Module takes care of locking for us which is a great Advantage.
Output
Consumer waiting for updation
Producer Producing Item: 58
Producer giving Notification
Consumer consumed the item: 58
Types of Queues:
Python Supports 3 Types of Queues.
1) FIFO Queue:
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).
1) import queue
2) q=queue.Queue()
3) q.put(10)
4) q.put(5)
5) q.put(20)
6) q.put(15)
7) while not q.empty():
8) print(q.get(),end=' ')
Output: 10 5 20 15
1) import queue
2) q=queue.LifoQueue()
3) q.put(10)
4) q.put(5)
5) q.put(20)
6) q.put(15)
7) while not q.empty():
8) print(q.get(),end=' ')
Output: 15 20 5 10
3) Priority Queue:
The elements will be inserted based on some priority order.
1) import queue
2) q=queue.PriorityQueue()
3) q.put(10)
4) q.put(5)
5) q.put(20)
6) q.put(15)
7) while not q.empty():
8) print(q.get(),end=' ')
Output: 5 10 15 20
Eg 2: If the data is non-numeric, then we have to provide our data in the form of tuple.
(x,y)
x is priority
y is our element
1) import queue
2) q=queue.PriorityQueue()
3) q.put((1,"AAA"))
4) q.put((3,"CCC"))
5) q.put((2,"BBB"))
6) q.put((4,"DDD"))
7) while not q.empty():
8) print(q.get()[1],end=' ')
l = threading.Lock()
l.acquire()
try:
perform required safe
operations finally:
l.release()
Demo Program:
1) from threading import *
2) import time
3) l=Lock()
4) def wish(name):
5) l.acquire()
6) try:
7) for i in range(10):
8) print("Good Evening:",end='')
9) time.sleep(2)
10) print(name)
11) finally:
12) l.release()
13)
14) t1=Thread(target=wish,args=("Dhoni",))
15) t2=Thread(target=wish,args=("Yuvraj",))
16) t3=Thread(target=wish,args=("Kohli",))
17) t1.start()
18) t2.start()
19 t3.start()
)
Case-2:
It is highly recommended to acquire lock by using with statement. The main
advantage 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.
Demo Program:
1) from threading import *
2) import time
3) lock=Lock()
4) def wish(name):
5) with lock:
6) for i in range(10):
7) print("Good Evening:",end='')
8) time.sleep(2)
9) print(name)
10) t1=Thread(target=wish,args=("Dhoni",))
11) t2=Thread(target=wish,args=("Yuvraj",))
12) t3=Thread(target=wish,args=("Kohli",))
13) t1.start()
14) t2.start()
15) t3.start()
Note: We can use with statement in multithreading for the following cases:
1) Lock
2) RLock
3) Semaphore
4) Condition
To store this Data, we required Storage Areas. There are 2 types of Storage Areas.
File Systems:
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.
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.
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.
153 DURGASOFT, # 202, 2nd Floor, HUDA Maitrivanam, Ameerpet,
Hyderabad - 500038,
040 – 64 51 27 86, 80 96 96 96 96, 92 46 21 21 43 |
Limitations of Databases:
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 Data) and cannot provide support for Semi Structured Data (like XML Files)
and Unstructured Data (like Video Files, Audio Files, Images etc)
To overcome these Problems we should go for more Advanced Storage Areas like Big Data
Technologies, Data warehouses etc.
3) To execute our sql queries and to hold results some special object is required, which is
nothing but Cursor object. We can create Cursor object by using cursor() method.
cursor = con.cursor()
4) Execute SQL Queries By using Cursor object. For this we can use the following methods
⚽ execute(sqlquery) To execute a Single SQL Query
⚽ executescript(sqlqueries) To execute a String of SQL Queries seperated by semi-
colon ';'
⚽ executemany() To execute a Parameterized Query.
Eg: cursor.execute("select * from employees")
6) Fetch the result from the Cursor object in the case of select queries
fetchone() To fetch only one row
fetchall() To fetch all rows and it returns a list of rows
fecthmany(n) To fetch first n rows
Eg 1: data = cursor.fetchone()
print(data)
Eg 2: data =
cursor.fetchall() for
row in data:
print(row)
Note: The following is the list of all important methods which can be used for python
database programming.
⚽ connect()
⚽ cursor()
⚽ execute()
⚽ executescript()
⚽ executemany()
⚽ commit()
⚽ rollback()
⚽ fetchone()
⚽ fetchall()
⚽ fetchmany(n)
⚽ fetch
⚽ close()
These methods won't be changed from database to database and same for all databases.
Diagram
Installing cx_Oracle:
From Normal Command Prompt (But not from Python console) execute the following
command
Collecting cx_Oracle
Downloading cx_Oracle-6.0.2-cp36-cp36m-win32.whl
(100kB) 100% | | 102kB 256kB/s
Installing collected packages: cx-Oracle
Successfully installed cx-Oracle-6.0.2
Output D:\
python_classes>py db1.py
11.2.0.2.0
1) import cx_Oracle
2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor()
5) cursor.execute("create table employees(eno number,ename varchar2(10),esal n
umber(10,2),eaddr varchar2(10))")
6) print("Table created successfully")
7) except cx_Oracle.DatabaseError as e:
8) if con:
9) con.rollback()
10) print("There is a problem with sql",e)
11) finally:
12) if cursor:
13) cursor.close()
14) if con:
15) con.close()
1) import cx_Oracle
2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor()
5) increment=float(input("Enter Increment Salary:"))
6) salrange=float(input("Enter Salary Range:"))
7) sql="update employees set esal=esal+%f where esal<%f"
8) cursor.execute(sql %(increment,salrange))
9) print("Records Updated Successfully")
10) con.commit()
11) except cx_Oracle.DatabaseError as e:
12) if con:
13) con.rollback()
14) print("There is a problem with sql :",e)
15) finally:
16) if cursor:
17) cursor.close()
18) if con:
19) con.close()
1) import cx_Oracle
2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor()
5) cutoffsalary=float(input("Enter CutOff Salary:"))
1) import cx_Oracle
2) try:
3) con=cx_Oracle.connect('scott/tiger@localhost')
4) cursor=con.cursor()
5) cursor.execute("select * from employees")
6) n=int(input("Enter the number of required rows:"))
7) data=cursor.fetchmany(n)
8) for row in data:
9) print(row)
10) except cx_Oracle.DatabaseError as e:
11) if con:
12) con.rollback()
13) print("There is a problem with sql :",e)
14) finally:
15) if cursor:
16) cursor.close()
17) if con:
18) con.close()
D:\python_classes>py test.py
Enter the number of required rows:4
(100, 'Durga', 1500.0, 'Hyd')
(200, 'Sunny', 2500.0, 'Mumbai')
(300, 'Chinny', 3500.0, 'Hyd')
(400, 'Bunny', 4500.0, 'Hyd')
Note: In MySQL, everything we have to work with our own databases, which are also
known as Logical Databases.
In the above diagram only one physical database is available and 4 logical databases are
available.
5) To Create a Table
create table employees(eno int(5) primary key,ename varchar(10),esal double(10,2),
eaddr varchar(10));
6) To Insert Data
insert into employees values(100,'Durga',1000,'Hyd');
insert into employees values(200,'Ravi',2000,'Mumbai');
Driver/Connector Information:
From Python program if we want to communicates with MySql database, compulsory
some translator is required to convert python specific calls into mysql database specific
calls and mysql database specific calls into python specific calls. This translator is nothing
but Driver or Connector.
Note: In the case of Python3.4 we have to set PATH and PYTHONPATH explicitly
PATH=C:\Python34
PYTHONPATH=C:\Python34\Lib\site-packages
https://dev.mysql.com/downloads/connector/python/2.1.html
1) compile()
Returns Module contains compile() Function to compile a Pattern into RegexObject.
pattern = re.compile("ab")
2) finditer():
Returns an Iterator object which yields Match object for every Match
matcher = pattern.finditer("abaababa")
1) import re count=0
2) pattern=re.compile("ab")
3) matcher=pattern.finditer("abaababa")
4) for match in matcher:
5) count+=1
6) print(match.start(),"...",match.end(),"...",match.group())
7) print("The number of occurrences: ",count)
Output:
0 ... 2 ... ab
3 ... 5 ... ab
5 ... 7 ... ab
1) import re
2) count=0
3) matcher=re.finditer("ab","abaababa")
4) for match in matcher:
5) count+=1
6) print(match.start(),"...",match.end(),"...",match.group())
7) print("The number of occurrences: ",count)
Output:
0 ... 2 ... ab
3 ... 5 ... ab
5 ... 7 ... ab
The number of occurrences: 3
Character Classes:
We can use character classes to search a group of characters
1) [abc] Either a OR b OR c
2) [^abc] Except a and b and c
3) [a-z] Any Lower case alphabet symbol
4) [A-Z] Any upper case alphabet symbol
5) [a-zA-Z] Any alphabet symbol
6) [0-9] Any digit from 0 to 9
7) [a-zA-Z0-9] Any alphanumeric character
8) [^a-zA-Z0-9] Except alphanumeric characters(Special Characters)
1) import re
2) matcher=re.finditer("x","a7b@k9z")
3) for match in matcher:
4) print(match.start(),"......",match.group())
1) import re
2) matcher=re.finditer("x","a7b k@9z")
3) for match in matcher:
4) print(match.start(),"......",match.group())
x = \s: x = \S: x = \d: x = \D: x = \w: x = \W: x=.
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
4.......k 4.......k 4.......k 3 ......
5.......@ 5.......@ 6.......9 4.......k
6.......9 7.......z 7.......z 5.......@
7.......z 6.......9
7.......z
Qunatifiers:
We can use quantifiers to specify the number of occurrences to match.
1) a Exactly one 'a'
2) a+ Atleast one 'a'
3) a* Any number of a's including zero number
4) a? Atmost one 'a' ie either zero number or one number
5) a{m} Exactly m number of a's
6) a{m,n} Minimum m number of a's and Maximum n number of a's.
1) import re
2) matcher=re.finditer("x","abaabaaab")
3) for match in matcher:
4) print(match.start(),"......",match.group())
x = a?:
0 a
x = a: x = a+: x = a*: x = a{3}: x = a{2,4}:
1 ......
0.......a 0.......a 0.......a 5.......aaa 2.......aa
2........a
2.......a 2.......aa 1 ...... 5.......
3........a
3.......a 5.......aaa 2.......aa aaa
4 ......
5.......a 4 ......
5........a
6.......a 5.......aaa
6........a
7.......a 8 ......
9 ...... 7........a
8 ......
9 ......
1) match():
We can use match function to check the given pattern at beginning of target string.
If the match is available then we will get Match object, otherwise we will get None.
1) import re
2) s=input("Enter pattern to check: ")
3) m=re.match(s,"abcabdefg")
4) if m!= None:
5) print("Match is available at the beginning of the String")
6) print("Start Index:",m.start(), "and End Index:",m.end())
7) else:
8) print("Match is not available at the beginning of the String")
Output:
D:\python_classes>py test.py
Enter pattern to check: abc
Match is available at the beginning of the String
Start Index: 0 and End Index: 3
D:\python_classes>py test.py
Enter pattern to check: bde
Match is not available at the beginning of the String
2) fullmatch():
We can use fullmatch() function to match a pattern to all of target string. i.e complete
string should be matched according to given pattern.
If complete string matched then this function returns Match object otherwise
it returns None.
Output:
D:\python_classes>py test.py
Enter pattern to check: ab
Full String not Matched
3) search():
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.
If the match is not available then it returns None
1) import re
2) s=input("Enter pattern to check: ")
3) m=re.search(s,"abaaaba")
4) if m!= None:
5) print("Match is available")
6) print("First Occurrence of match with start index:",m.start(),"and end index:",m.
end())
7) else:
8) print("Match is not available")
Output:
D:\python_classes>py test.py
Enter pattern to check: aaa
Match is available
First Occurrence of match with start index: 2 and end index: 5
D:\python_classes>py test.py
Enter pattern to check: bbb
Match is not available
1) import re
2) l=re.findall("[0-9]","a7b9c5kz")
3) print(l)
5) finditer():
Returns the iterator yielding a match object for each match.
On each match object we can call start(), end() and group() functions.
1) import re
2) itr=re.finditer("[a-z]","a7b9c5k8z")
3) for m in itr:
4) print(m.start(),"...",m.end(),"...",m.group())
6) sub():
sub means substitution or replacement.
re.sub(regex,replacement,targetstring)
In the target string every matched pattern will be replaced with provided replacement.
1) import re
2) s=re.sub("[a-z]","#","a7b9c5k8z")
3) print(s)
Output: #7#9#5#8#
Every alphabet symbol is replaced with # symbol
7) subn():
It is exactly same as sub except it can also returns the number of replacements.
This function returns a tuple where first element is result string and second element is
number of replacements.
(resultstring, number of replacements)
Output:
D:\python_classes>py test.py
('#7#9#5#8#', 5)
The Result String: #7#9#5#8#
The number of replacements: 5
8) split():
If we want to split the given target string according to a particular pattern then we
should go for split() function.
This function returns list of all tokens.
1) import re
2) l=re.split(",","sunny,bunny,chinny,vinny,pinny")
3) print(l)
4) for t in l:
5) print(t)
Output:
D:\python_classes>py test.py
['sunny', 'bunny', 'chinny', 'vinny', 'pinny']
sunny
bunny
chinny
vinny
pinny
1) import re
2) l=re.split("\.","www.durgasoft.com")
3) for t in l:
4) print(t)
Output: D:\
python_classes>py test.py
www
durgasoft
com
test.py
1) import re
2) s="Learning Python is Very Easy"
3) res=re.search("^Learn",s)
4) if res != None:
5) print("Target String starts with Learn")
6) else:
7) print("Target String Not starts with Learn")
10) $ symbol:
We can use $ symbol to check whether the given target string ends with
our provided pattern or not.
Eg: res = re.search("Easy$",s)
If the target string ends with Easy then it will return Match
object,otherwise returns None.
test.py
1) import re
2) s="Learning Python is Very Easy"
3) res=re.search("Easy$",s)
4) if res != None:
5) print("Target String ends with Easy")
6) else:
7) print("Target String Not ends with Easy")
Note: If we want to ignore case then we have to pass 3rd argument re.IGNORECASE for
search() function.
Eg: res = re.search("easy$",s,re.IGNORECASE)
1) import re
2) s="Learning Python is Very Easy"
3) res=re.search("easy$",s,re.IGNORECASE)
4) if res != None:
5) print("Target String ends with Easy by ignoring case")
6) else:
7) print("Target String Not ends with Easy by ignoring case")
Output D:\
python_classes>py test.py
Enter Identifier:a6kk9z##
a6kk9z## is valid Yava Identifier
D:\python_classes>py test.py
Enter Identifier:k9b876
k9b876 is valid Yava Identifier
D:\python_classes>py test.py
Enter Identifier:k7b9
k7b9 is invalid Yava Identifier
[7-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]
OR
[7-9][0-9]{9}
OR
[7-9]\d{9}
Output D:\
python_classes>py test.py
Enter number:9898989898
Valid Mobile Number
D:\python_classes>py test.py
Enter number:6786786787
Invalid Mobile Number
D:\python_classes>py test.py
Enter number:898989
Invalid Mobile Number
1) import re
2) f1=open("input.txt","r")
3) f2=open("output.txt","w")
1) import re,urllib
2) import urllib.request
3) sites="google rediff".split()
4) print(sites)
5) for s in sites:
6) print("Searching...",s)
7) u=urllib.request.urlopen("http://"+s+".com")
8) text=u.read()
9) title=re.findall("<title>.*</title>",str(text),re.I)
10) print(title[0])
Output:
D:\python_classes>py test.py
Enter Mail
id:[email protected] Valid Mail
Id
D:\python_classes>py test.py
Enter Mail id:durgatoc
Invalid Mail id
D:\python_classes>py test.py
Enter Mail id:[email protected]
Invalid Mail id
Output:
D:\python_classes>py test.py
Enter Vehicle Registration Number:TS07EA7777
Valid Vehicle Registration Number
D:\python_classes>py test.py
Enter Vehicle Registration Number:TS07KF0786
Valid Vehicle Registration Number
D:\python_classes>py test.py
Enter Vehicle Registration Number:AP07EA7898
Invalid Vehicle Registration Number
The main objective of decorator functions is we can extend the functionality of existing
functions without modifies that function.
1) def wish(name):
2) print("Hello",name,"Good Morning")
This function can always print same output for any name
But we want to modify this function to provide different message if name is Sunny.
We can do this without touching wish() function by using decorator.
1) def decor(func):
2) def inner(name):
3) if name=="Sunny":
4) print("Hello Sunny Bad Morning")
5) else:
6) func(name)
7) return inner
8)
9) @decor
10) def wish(name):
11) print("Hello",name,"Good Morning")
12)
13) wish("Durga")
14) wish("Ravi")
15) wish("Sunny")
Output
Hello Durga Good Morning
Hello Ravi Good Morning
1) def decor(func):
2) def inner(name):
3) if name=="Sunny":
4) print("Hello Sunny Bad Morning")
5) else:
6) func(name)
7) return inner
8)
9) def wish(name):
10) print("Hello",name,"Good Morning")
11)
12) decorfunction=decor(wish)
13)
14) wish("Durga") #decorator wont be executed
15) wish("Sunny") #decorator wont be executed
16)
17) decorfunction("Durga")#decorator will be executed
18) decorfunction("Sunny")#decorator will be executed
Output
Hello Durga Good Morning
Hello Sunny Good Morning
Hello Durga Good Morning
Hello Sunny Bad Morning
1) def smart_division(func):
2) def inner(a,b):
3) print("We are dividing",a,"with",b)
4) if b==0:
5) print("OOPS...cannot divide")
6) return
7) else:
8) return func(a,b)
9) return inner
10)
11) @smart_division
12) def division(a,b):
13) return a/b
With Decorator we won't get any Error. In this Case Output is:
We are dividing 20 with 2
10.0
We are dividing 20 with 0
OOPS...cannot divide
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.
Generator
A Sequence of Values
Function
yield
1) def mygen():
2) yield 'A'
3) yield 'B'
4) yield 'C'
5)
6) g=mygen()
7) print(type(g))
8)
9) print(next(g))
10) print(next(g))
11) print(next(g))
12) print(next(g))
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
1) def firstn(num):
2) n=1
3) while n<=num:
4) yield n
5) n=n+1
6)
7) values=firstn(5)
8) for x in values:
9) print(x)
Output
1
2
3
4
5
Eg: 0,1,1,2,3,5,8,13,21,...
1) def fib():
2) a,b=0,1
3) while True:
4) yield a
5) a,b=b,a+b
6) for f in fib():
7) if f>100:
8) break
9) print(f)
Note: In the above program observe the differnce wrt execution time by using list and
generators
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
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"
Output
4
9
16
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
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
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.
The above line will create a file log.txt and we can store either WARNING level or higher
level messages to that file.
Q) Write a Python Program to create a Log File and write WARNING and
Higher Level Messages?
1) import logging
2) logging.basicConfig(filename='log.txt',level=logging.WARNING)
3) print('Logging Demo')
4) logging.debug('Debug Information')
5) logging.info('info Information')
6) logging.warning('warning Information')
7) logging.error('error Information')
8) logging.critical('critical Information')
log.txt:
WARNING:root:warning Information
ERROR:root:error Information
CRITICAL:root:critical Information
Note: In the above program only WARNING and higher level messages will be written to
the log file. If we set level as DEBUG then all messages will be written to the log file.
test.py
1) import logging
2) logging.basicConfig(filename='log.txt',level=logging.DEBUG)
3) print('Logging Demo')
4) logging.debug('Debug Information')
5) logging.info('info Information')
6) logging.warning('warning Information')
7) logging.error('error Information')
8) logging.critical('critical Information')
log.txt
DEBUG:root:Debug Information
INFO:root:info Information
WARNING:root:warning Information
ERROR:root:error Information
CRITICAL:root:critical Information
logging.basicConfig(filename='log786.txt',level=logging.WARNING)
Meant for appending
logging.basicConfig(filename='log786.txt',level=logging.WARNING,filemode='a')
Explicitly we are specifying appending.
logging.basicConfig(filename='log786.txt',level=logging.WARNING,filemode='w')
Meant for over writing of previous data.
Note:
logging.basicConfig(filename='log.txt',level=logging.DEBUG)
If we are not specifying level then the default level is WARNING(30)
If we are not specifying file name then the messages will be printed to the console.
test.py
1) import logging
2) logging.basicConfig()
3) print('Logging Demo')
4) logging.debug('Debug Information')
5) logging.info('info Information')
6) logging.warning('warning Information')
7) logging.error('error Information')
8) logging.critical('critical Information')
D:\durgaclasses>py test.py
Logging Demo
WARNING:root:warning Information
ERROR:root:error Information
CRITICAL:root:critical Information
Output
2018-06-15 11:50:08,325:WARNING:warning Information
2018-06-15 11:50:08,372:ERROR:error Information
2018-06-15 11:50:08,372:CRITICAL:critical Information
logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',
datefmt='%d/%m/%Y %I:%M:%S %p')
datefmt='%d/%m/%Y %I:%M:%S %p' Case is important
Output
15/06/2018 12:04:31 PM:WARNING:warning Information
15/06/2018 12:04:31 PM:ERROR:error Information
15/06/2018 12:04:31 PM:CRITICAL:critical Information
Note:
%I means 12 Hours time scale
%H means 24 Hours time scale
Eg: logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s',
datefmt='%d/%m/%Y %H:%M:%S')
Output:
15/06/2018 12:06:28:WARNING:warning Information
15/06/2018 12:06:28:ERROR:error Information
15/06/2018 12:06:28:CRITICAL:critical Information
https://docs.python.org/3/library/logging.html#logrecord-attributes
https://docs.python.org/3/library/time.html#time.strftime
D:\durgaclasses>py test.py
Enter First Number:10
Enter Second Number:2
The Result: 5.0
D:\durgaclasses>py test.py
Enter First Number:20
Enter Second Number:2
The Result: 10.0
D:\durgaclasses>py test.py
Enter First Number:10
Enter Second Number:0
cannot divide with zero
D:\durgaclasses>py test.py
Enter First Number:ten
Please provide int values
only
Demo Application:
student.py:
1) import logging
2) logging.basicConfig(filename='student.log',level=logging.INFO)
3) logging.info('info message from student module')
test.py:
1) import logging
2) import student
3) logging.basicConfig(filename='test.log',level=logging.DEBUG)
4) logging.debug('debug message from test module')
student.log:
INFO: root:info message from student module
1) Once we set basic configuration then that configuration is final and we cannot change.
2) It will always work for only one handler at a time, either console or file, but not
both simultaneously.
3) It is not possible to configure logger with different configurations at different levels.
4) We cannot specify multiple log files for multiple modules/classes/methods.
Note: Bydefault logger will set to WARNING level. But we can set our own level based on
our requirement.
logger = logging.getLogger('demologger')
logger.setLevel(logging.INFO)
logger log level by default available to console and file handlers. If we are not satisfied
with logger level, then we can set log level explicitly at console level and file levels.
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.WARNING)
fileHandler = logging.FileHandler('abc.log',mode='a')
fileHandler.setLevel(logging.ERROR)
Note: console and file log levels should be supported by logger. i.e logger log level should
be lower than console and file levels. Otherwise only logger log level will be considered.
Eg:
logger DEBUG console INFO Valid and INFO will be considered
logger INFO console DEBUG Invalid and only INFO will be considered to the
console.
D:\durgaclasses>py loggingdemo3.py
06/18/2018 12:14:15 PM - demologger - INFO: info message
06/18/2018 12:14:15 PM - demologger - WARNING: warn message
06/18/2018 12:14:15 PM - demologger - ERROR: error message
06/18/2018 12:14:15 PM - demologger - CRITICAL: critical message
Note: If we want to use class name as logger name then we have to create logger
object as follows logger =
logging.getLogger(LoggerDemoConsole. name )
D:\durgaclasses>py loggingdemo3.py
06/18/2018 12:21:00 PM - LoggerDemoConsole - INFO: info message
06/18/2018 12:21:00 PM - LoggerDemoConsole - WARNING: warn message
06/18/2018 12:21:00 PM - LoggerDemoConsole - ERROR: error message
06/18/2018 12:21:00 PM - LoggerDemoConsole - CRITICAL: critical message
abc.log:
07/05/2018 08:58:04 AM - demologger - INFO: info message
07/05/2018 08:58:04 AM - demologger - WARNING: warn message
07/05/2018 08:58:04 AM - demologger - ERROR: error message
07/05/2018 08:58:04 AM - demologger - CRITICAL: critical message
logging.config.fileConfig('logging.conf')
logger = logging.getLogger(LoggerDemoConf. name )
Note: The extension of the file need not be conf. We can use any extension like txt or
durga etc.
logging.conf
[loggers]
keys=root,LoggerDemoConf
[handlers]
keys=fileHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=fileHandler
[logger_LoggerDemoConf]
level=DEBUG
handlers=fileHandler
qualname=demoLogger
[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%m/%d/%Y %I:%M:%S %p
test.py
1) import logging
2) import logging.config
3) class LoggerDemoConf():
4) def testLog(self):
5) logging.config.fileConfig('logging.conf')
6) logger = logging.getLogger(LoggerDemoConf. name )
7)
8) logger.debug('debug message')
9) logger.info('info message')
10) logger.warn('warn message')
11) logger.error('error message')
12) logger.critical('critical message')
13)
14) demo = LoggerDemoConf()
15) demo.testLog()
test.log
06/18/2018 12:40:05 PM - LoggerDemoConf - DEBUG - debug message
06/18/2018 12:40:05 PM - LoggerDemoConf - INFO - info message
06/18/2018 12:40:05 PM - LoggerDemoConf - WARNING - warn message
06/18/2018 12:40:05 PM - LoggerDemoConf - ERROR - error message
06/18/2018 12:40:05 PM - LoggerDemoConf - CRITICAL - critical message
[handler_fileHandler]
class=FileHandler
level=INFO
formatter=simpleFormatter
args=('test.log', 'w')
[handler_fileHandler]
class=FileHandler
level=INFO
formatter=simpleFormatter
args=('test.log', 'a')
1) import logging
2) import inspect
3) def getCustomLogger(level):
4) # Get Name of class/method from where this method called
5) loggername=inspect.stack()[1][3]
6) logger=logging.getLogger(loggername)
7) logger.setLevel(level)
8)
9) fileHandler=logging.FileHandler('abc.log',mode='a')
10) fileHandler.setLevel(level)
11)
12) formatter = logging.Formatter('%(asctime)s - %(name)s -
%(levelname)s: %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
13) fileHandler.setFormatter(formatter)
14) logger.addHandler(fileHandler)
15)
16) return logger
test.py
1) import logging
2) from customlogger import getCustomLogger
3) class LoggingDemo:
4) def m1(self):
5) logger=getCustomLogger(logging.DEBUG)
6) logger.debug('m1:debug message')
7) logger.info('m1:info message')
8) logger.warn('m1:warn message')
9) logger.error('m1:error message')
10) logger.critical('m1:critical message')
11) def m2(self):
12) logger=getCustomLogger(logging.WARNING)
abc.log:
06/19/2018 12:17:19 PM - m1 - DEBUG: m1:debug message
06/19/2018 12:17:19 PM - m1 - INFO: m1:info message
06/19/2018 12:17:19 PM - m1 - WARNING: m1:warn message
06/19/2018 12:17:19 PM - m1 - ERROR: m1:error message
06/19/2018 12:17:19 PM - m1 - CRITICAL: m1:critical message
06/19/2018 12:17:19 PM - m2 - WARNING: m2:warn message
06/19/2018 12:17:19 PM - m2 - ERROR: m2:error message
06/19/2018 12:17:19 PM - m2 - CRITICAL: m2:critical message
06/19/2018 12:17:19 PM - m3 - ERROR: m3:error message
06/19/2018 12:17:19 PM - m3 - CRITICAL: m3:critical message
test.py:
#Same as previous
1) import logging
2) from customlogger import getCustomLogger
3) class LoggingDemo:
4) def m1(self):
5) logger=getCustomLogger(logging.DEBUG)
6) logger.debug('m1:debug message')
7) logger.info('m1:info message')
8) logger.warn('m1:warn message')
9) logger.error('m1:error message')
10) logger.critical('m1:critical message')
11) def m2(self):
12) logger=getCustomLogger(logging.WARNING)
13) logger.debug('m2:debug message')
14) logger.info('m2:info message')
15) logger.warn('m2:warn message')
16) logger.error('m2:error message')
17) logger.critical('m2:critical message')
18) def m3(self):
19) logger=getCustomLogger(logging.ERROR)
20) logger.debug('m3:debug message')
21) logger.info('m3:info message')
22) logger.warn('m3:warn message')
23) logger.error('m3:error message')
24) logger.critical('m3:critical message')
25)
26) l=LoggingDemo()
27) print('Logging Demo with Seperate Log File')
28) l.m1()
29) l.m2()
30) l.m3()
m1.log
06/19/2018 12:26:04 PM - m1 - DEBUG: m1:debug message
06/19/2018 12:26:04 PM - m1 - INFO: m1:info message
06/19/2018 12:26:04 PM - m1 - WARNING: m1:warn message
m2.log
06/19/2018 12:26:04 PM - m2 - WARNING: m2:warn message
06/19/2018 12:26:04 PM - m2 - ERROR: m2:error message
06/19/2018 12:26:04 PM - m2 - CRITICAL: m2:critical message
m3.log
06/19/2018 12:26:04 PM - m3 - ERROR: m3:error message
06/19/2018 12:26:04 PM - m3 - CRITICAL: m3:critical message
1) import logging
2) import inspect
3) def getCustomLogger(level):
4) loggername=inspect.stack()[1][3]
5)
6) logger=logging.getLogger(loggername)
7) logger.setLevel(level)
8) fileHandler=logging.FileHandler('test.log',mode='a')
9) fileHandler.setLevel(level)
10) formatter=logging.Formatter('%(asctime)s - %(name)s -
%(levelname)s: %(message)s',datefmt='%m/%d/%Y %I:%M:%S %p')
11) fileHandler.setFormatter(formatter)
12) logger.addHandler(fileHandler)
13) return logger
test.py
1) import logging
2) from customlogger import getCustomLogger
3) class Test:
4) def logtest(self):
5) logger=getCustomLogger(logging.DEBUG)
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()