0% found this document useful (0 votes)
3 views264 pages

Adavance Python

This document provides an overview of Python classes, including definitions of attributes and methods, how to create classes and objects, and the differences between instance and class variables. It also explains the concepts of constructors, instance methods, class methods, and static methods, along with examples of their usage. Additionally, it discusses the importance of the 'self' variable and the namespace in Python classes.

Uploaded by

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

Adavance Python

This document provides an overview of Python classes, including definitions of attributes and methods, how to create classes and objects, and the differences between instance and class variables. It also explains the concepts of constructors, instance methods, class methods, and static methods, along with examples of their usage. Additionally, it discusses the importance of the 'self' variable and the namespace in Python classes.

Uploaded by

akasha804428
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Class

A Python class is a group of attributes and methods.

What is Attribute ?
Attributes are represented by variable that contains data.

What is Method?
Method performs an action or task. It is similar to function.
How to Create Class
class Classname(object) : class Classname :
def __init__(self): def __init__(self):
self.variable_name = value self.variable_name = value
Method Attributes self.variable_name = ‘value’
self.variable_name = ‘value’
def method_name(self):
def method_name(self): Body of Method
Body of Method

• class - class keyword is used to create a class


• object - object represents the base class name from where all classes in Python are derived.
This class is also derived from object class. This is optional.
• __init__() – This method is used to initialize the variables. This is a special method. We do
not call this method explicitly.
• self – self is a variable which refers to current class instance/object.
Rules
• The class name can be any valid identifier.
• It can't be Python reserved word.
• A valid class name starts with a letter, followed by any number
of letter, numbers or underscores.
• A class name generally starts with Capital Letter.
How to Create Class
class Mobile:
def __init__(self):
[Link] = ‘RealMe X’
def show_model (self):
print(‘Model:’, [Link])
How to Create Class
Formal Argument
class Classname : class Classname :
def __init__(self): def __init__(self, f1, f2):
self.variable_name = value self.variable_name = value
self.variable_name = ‘value’ self.variable_name = ‘value’

def method_name(self): def method_name(self):


Body of Method Formal Argument Body of Method Formal Argument

def method_name(self, f1, f2): def method_name(self, f1, f2):


Body of Method Body of Method
How to Create Class
class Mobile:
def __init__(self, m):
[Link] = m
def show_model (self, p):
price = p # Local Variable
print(‘Model:’, [Link], ‘Price:’, price)
Object
Object is class type variable or class instance. To use a class, we should create an object to the
class.
Instance creation represents allotting memory necessary to store the actual data of the variables.
Each time you create an object of a class a copy of each variables defined in the class is created.
In other words you can say that each object of a class has its own copy of data members defined in
the class.
Syntax: -
object_name = class_name()
object_name = class_name(arg)
How to Create Object
class Mobile: class Mobile:
def __init__(self): def __init__(self, m):
[Link] = ‘RealMe X’ [Link] = m
def show_model (self): def show_model (self):
print(‘Model:’, [Link]) print(‘Model:’, [Link])

realme = Mobile() realme = Mobile(‘RealMe X’)


How it works
realme = Mobile()
• A block of memory is allocated on heap. The size of allocated memory is to
be decided from the attributes and methods available in the class (Mobile).
• After allocating memory block, the special method __init__() is called
internally. This method stores the initial data into the variables.
• The allocated memory location address of the instance is returned into
object (realme).
• The memory location is passed to self.
Accessing class member using object
We can access variable and method of a class using class object or instance of class.

object_name.variable_name
[Link]

object_name.method_name ( )
realme.show_model ( );

object_name.method_name (parameter_list)
realme.show_model(1000);
class

RealMe Redmi
self Variable
self is a default variable that contains the memory address of the current object.
This variable is used to refer all the instance variable and method.
When we create object of a class, the object name contains the memory location of the
object.
This memory location is internally passed to self, as self knows the memory address of
the object so we can access variable and method of object.
self is the first argument to any object method because the first argument is always the
object reference. This is automatic, whether you call it self or not.

def __init__(self):

def show_model(self):
Object
Each time you create an object of a class a copy of each variables defined in the class is
created.
class Mobile:
def __init__(self):
[Link] = ‘RealMe X’
def show_model (self):
print(‘Model:’, [Link])

realme = Mobile()
redmi = Mobile()
geek = Mobile()
Constructor
Python supports a special type of method called constructor for initializing the
instance variable of a class.
A class constructor, if defined is called whenever a program creates an object
of that class.
A constructor is called only once at the time of creating an instance.
If two instances are created for a class, the constructor will be called once for
each instance.
Constructor without Parameter
class Mobile:
def __init__(self):
[Link] =‘RealMe X’

realme = Mobile( )
Constructor with Parameter
class Mobile:
def __init__(self, m):
[Link] = m
realme = Mobile('Realme X')

class Mobile:
def __init__(self, m, v=80):
[Link] = m
[Link] = v
redmi = Mobile('Redmi 7s', 50)
Type of Variable
• Instance Variable
• Class Variable / Static Variable
Instance Variable
Instance variables are the variables whose separate copy is created in every object.
Instance variables are defined and initialized using a constructor with self parameter.
Ex:-
class Mobile:
def __init__(self):
[Link] = ‘RealMe X’ Instance Variable

def show_model(self):
print([Link])
realme = Mobile( )
Accessing Instance Variable
With Instance Method
To access instance variable, we need instance methods with self as first parameter then
we can access instance variable using self.variable_name
class Mobile:
def __init__(self):
Instance Variable
[Link] = ‘RealMe X’
def show_model(self): Instance Method

[Link]
realme = Mobile( ) Accessing Instance Variable
Accessing Instance Variable
Outside Class
We can access instance variable using object_name.variable_name
class Mobile:
def __init__(self):
[Link] = ‘RealMe X’ Instance Variable

def show_model(self): Instance Method


[Link]
Accessing Instance Variable
realme = Mobile( )
[Link] Accessing Instance Variable from outside Class
Instance Variable
Instance variables are the variables whose separate copy is created in every object.
If we modify the copy of Instance variable in an instance, it will not effect all the
copies in the other instance. Heap Memory
class Mobile:
def __init__(self): Instance Variable [Link] = ‘RealMe X’

[Link] = ‘RealMe X’ realme

def show_model(self):
print([Link]) [Link] = ‘RealMe X’

realme = Mobile( ) redmi

redmi = Mobile( )
geek = Mobile( ) [Link] = ‘RealMe X’
geek
Class Variable / Static Variable
Class variables are the variables whose single copy is available to all the instance of the class.
If we modify the copy of class variable in an instance, it will effect all the copies in the other
instance.
Ex:-
class Mobile:
fp = ‘Yes’ Class Variable

def __init__(self):
[Link] = ‘RealMe X’

def show_model(self):
print([Link])

realme = Mobile( )
Accessing Class/Static Variable
With Class Method
To access class variable, we need class methods with cls as first parameter then we can access
class variable using cls.variable_name
class Mobile:
fp = ‘Yes’ Class Variable
def __init__(self):
[Link] = ‘RealMe X’
def show_model(self):
print([Link])
@classmethod Class Method
def is_fp(cls):
[Link] Accessing Class Variable inside Class Method

realme = Mobile( )
Accessing Class/Static Variable
Outside Class
We can access class variable using Classname.variable_name
class Mobile:
fp = ‘Yes’ Class Variable

@classmethod Class Method


def show(cls):
[Link] Accessing Class Variable inside Class Method

realme = Mobile( )

[Link] Accessing Class Variable outside class


Class Variable / Static Variable
Class variables are the variables whose single copy is available to all the instance of the class. If
we modify the copy of class variable in an instance, it will effect all the copies in the other
instance.
class Mobile:
fp = ‘Yes’
fp = ‘Yes’
@classmethod
def is_fp(cls): realme redmi geek
print([Link])
Heap Memory
realme = Mobile( )
redmi = Mobile( )
geek = Mobile( )
print([Link])
Namespace
In Python, Namespace represents a memory block where names are mapped to
objects.

Class Namespace – A class maintains it’s own namespace known as class


namespace. In the class namespace, the names are mapped to class variables.

Instance Namespace – Every instance have it’s own namespace known as


instance namespace. In the instance namespace, the names are mapped to
instance variables.
Namespace
class Mobile:
Class Variable fp yes
no Class Namespace
fp = yes

realme = Mobile() realme redmi geek Instance Namespace


redmi = Mobile()
Not Working
geek = Mobile()

[Link] = no [Link] = Not Working


[Link] # yes
[Link] # no [Link] # no
[Link] # yes [Link] # no [Link] # Not Working
[Link] # yes [Link] # no [Link] # no
[Link] # yes [Link] # no [Link] # no
Type of Methods
• Instance Methods
– Accessor Methods
– Mutator Methods

• Class Methods

• Static Methods
Instance Method
Instance methods are the methods which act upon the instance variables of the class.
Instance method need to know the memory address of the instance which is provided
through self variable by default as first parameter for the instance method.
Syntax:-
def method_name(self): Instance Method without Parameter/Formal Arguments
function body

def method_name(self, f1, f2):


Instance Method with Parameter/Formal Arguments
function body
Instance Method without Parameter
class Mobile: Instance Method class Mobile: Instance variable
def __init__(self):
def show_model(self): [Link] = ‘RealMe X’
print(“RealMe X”)
def show_model(self): Instance Method

realme = Mobile( ) print([Link])


Accessing Instance variable
realme = Mobile( ) Inside Instance Method
Calling Instance Method w/o Argument
Instance methods are bound to object of the class so we call instance method with
object name.
Syntax:- object_name.method_name()
Ex:- realme.show_model()

class Mobile:
def show_model(self):
print(“RealMe X”)

realme = Mobile( )
realme.show_model() Calling Instance Method w/o Argument
Instance Method with Parameter
class Mobile: Instance variable
def __init__(self):
[Link] = ‘RealMe X’
Instance Method with parameter

def show_model(self, p):


Instance Variable [Link] = p Parameter
print([Link], [Link])

realme = Mobile( )
Calling Instance Method with Argument
Syntax:- object_name.method_name(Actual_argument)
Ex:- realme.show_model(1000)
class Mobile:
def __init__(self):
[Link] = ‘RealMe X’
def show_model(self, p):
[Link] = p
print([Link], [Link])

realme = Mobile( )
realme.show_model(1000) Calling Method with argument
Accessor Method
This method is used to access or read data of the variables. This method do not modify
the data in the variable. This is also called as getter method.
Ex:- class Mobile:
def get_value(self): def __init__(self):
def get_result(self): [Link] = ‘RealMe X’
def get_name(self):
def get_id(self): def get_model(self):
return [Link]

realme = Mobile( )
m = realme.get_model()
print(m)
Mutator Method
This method is used to access or read and modify data of the variables. This method
modify the data in the variable. This is also called as setter method.
Ex:- class Mobile: class Mobile:
def set_value(self): def __init__(self):
def set_result(self): [Link] = ‘RealMe X’ def set_model(self, m):
def set_name(self): [Link] = m
def set_id(self): def set_model(self):
[Link] = ‘RealMe 2’ realme = Mobile( )
realme.set_model(‘RealMe X’)
realme = Mobile( )
realme.set_model()
Class Methods
Class methods are the methods which act upon the class variables or static variable of
the class.
Decorator @classmethod need to write above the class method.
By default, the first parameter of class method is cls which refers to the class itself.
Syntax:-
Decorator
@classmethod
def method_name(cls):
Class Method without Parameter/Formal Arguments
method body
Decorator
@classmethod
def method_name(cls, f1, f2): Class Method with Parameter/Formal Arguments
method body
Class Method without Parameter
class Mobile: Decorator
class Mobile: Class Variable
@classmethod fp = ‘Yes’ Decorator
Class Method
def show_model(cls): @classmethod
print(“RealMe X”) def show_model(cls): Class Method

print([Link])
realme = Mobile( ) Accessing Class variable
realme = Mobile( ) Inside Class Method
Calling Class Method without Argument
Syntax:- Classname.method_name()

class Mobile:
@classmethod
def show_model(cls):
print(“RealMe X”)

realme = Mobile( )
Mobile.show_model() Calling Class Method w/o Argument
Class Method with Parameter
Class Variable class Mobile:
fp = ‘Yes’
Defining Method with parameter
Decorator @classmethod
def show_model(cls, r):
[Link] = r
print([Link], [Link])

realme = Mobile( )
Calling Class Method with Argument
Syntax:- Classname.method_name(Actual_argument)
Ex:- Mobile.show_model(‘4GB’)
class Mobile:
fp = ‘Yes’
@classmethod
def show_model(cls, r):
[Link] = r
print([Link], [Link])

realme = Mobile( )
Mobile.show_model(101) Calling Method with argument
Static Methods
Static Methods are used when some processing is related to the class but does not need the class
or its instances to perform any work.
We use static method when we want to pass some values from outside and perform some action in
the method.
Decorator @staticmethod need to write above the static method.
Syntax:- Decorator
@staticmethod
def method_name(): Static Method without Parameter/Formal Arguments
method body
Decorator
@staticmethod
def method_name(f1, f2):
Static Method with Parameter/Formal Arguments
method body
Static Method without Parameter
class Mobile: Decorator
class Mobile:
@staticmethod fp = ‘Yes’
Static Method
def show_model(): @staticmethod Static Method

print(“RealMe X”) def show_model():


print([Link])
realme = Mobile( )
realme = Mobile( )
Calling Static Method without Argument
Syntax:- Classname.method_name()

class Mobile:
@staticmethod
def show_model():
print(“RealMe X”)

realme = Mobile( )
Mobile.show_model() Calling Static Method w/o Argument
Static Method with Parameter
class Mobile:
Decorator @staticmethod Defining Method with parameter
def show_model(m, p):
model = m
price = p
print(model, price)
realme = Mobile( )
Calling Static Method with Argument
Syntax:- Classname.method_name(Actual_argument)
Ex:- Mobile.show_model(1000)
class Mobile:
@staticmethod
def show_model(m, p):
model = m
price = p
print(model, price)
realme = Mobile( )
Mobile.show_model(‘RealMe X’, 1000) Calling Method with argument
Nested Class
A class within a class is called as nested class or nesting of a class.
class OuterClassName:
def __init__(self):
self.variable_name = value
[Link] = [Link]( ) Inner Class Object
def method_name(self):
method body

class InnerClassName:
def __init__(self):
self.variable_name = value
def method_name(self):
method body
class Army: Outer Class
def __init__(self):
[Link] = ‘Rahul’
[Link] = [Link]() Inner Class Object
def show(self):
print([Link])
class Gun: Inner Class
def __init__(self):
[Link] = ‘AK47’
[Link] = ’75 Rounds’
[Link] = ‘34.3 in’
def disp(self):
print([Link], [Link], [Link])
a = Army() Outer Class Object
Inheritance
The mechanism of deriving a new class from an old one (existing class) such that the
new class inherit all the members (variables and methods) of old class is called
inheritance or derivation.

Old Class

New Class
Super Class and Sub Class
The old class is referred to as the Super class and the new one is called the Sub class.
• Parent Class - Base Class or Super Class
• Child Class - Derived Class or Sub Class

Father
• Home
Parent Class • Money
• Business

Son
Child Class •

BMW
Job
Inheritance
• All classes in python are built from a single super class called ‘object’ so
whenever we create a class in python, object will become super class for
them internally.
class Mobile(object):
class Mobile:

• The main advantage of inheritance is code reusability.


Why do We need inheritance
class Employee : class Manager :
id = 1 id = 1
@classmethod @classmethod
def getid(cls): def getid(cls):
return [Link] return [Link]
def setname(self, name): def setname(self, name):
[Link] = name [Link] = name
def getname(self): def getname(self):
return [Link] return [Link]
def setsalary(self, salary): def setsalary(self, salary):
[Link] = salary [Link] = salary
def getsalary(self): def getsalary(self):
return [Link] return [Link]
def setovertime(self, ot): def setseniorname(self, sname):
[Link] = ot [Link] = sname
def getovertime(self): def getseniorname(self):
return [Link] return [Link]
Parent Class Child Class
class Employee : class Manager :
id = 1 def setsalary(self, salary):
@classmethod
[Link] = salary
def getid(cls):
def getsalary(self):
return [Link]
def setname(self, name): return [Link]
[Link] = name def getseniorname(self, sname):
def getname(self): [Link] = sname
return [Link] def getseniorname(self):
def setsalary(self, salary): return [Link]
[Link] = salary
def getsalary(self):
return [Link]
def setovertime(self, ot):
[Link] = ot
def getovertime(self):
return [Link]
Type of Inheritance
• Single Inheritance

• Multi-level Inheritance

• Hierarchical Inheritance

• Multiple Inheritance
Declaration of Child Class
class ChildClassName (ParentClassName) :
members of Child class

class Mobile (object) :


members of Child class

class Mobile :
members of Child class
Single Inheritance
If a class is derived from one base class (Parent Class), it is called Single
Inheritance.
object

Father Parent Class

Son Child Class


Syntax:-
class ParentClassName(object): Parent Class
members of Parent Class

class ChildClassName(ParentClassName): Child Class


members of Child Class

Example:-
class Father: Father
members of class Father Parent Class

class Son (Father): Son


Child Class
members of class Son
Inheritance
• We can access Parent Class Variables and Methods using Child Class
Object

• We can also access Parent Class Variables and Methods using Parent Class
Object

• We can not access Child Class Variables and Methods using Parent Class
Object
Constructor in Inheritance
By default, The constructor in the parent class is available to the child class.
class Father:
def __init__(self):
[Link] = 2000
print("Father Class Constructor") What will happen if we define
constructor in both classes ?
class Son (Father):
def disp(self):
print(“Son Class Instance Method:”,[Link])

s = Son( )
[Link]()
Constructor Overriding
If we write constructor in the both classes, parent class and child class then the
parent class constructor is not available to the child class.
In this case only child class constructor is accessible which means child class
constructor is replacing parent class constructor.
Constructor overriding is used when programmer want to modify the existing
behavior of a constructor.
Constructor Overriding
class Father:
def __init__(self):
[Link] = 2000
print("Father Class Constructor")
How can we call parent
class Son(Father): class constructor ?
def __init__(self):
[Link] = 5000
print("Son Class Constructor")
def disp(self):
print([Link])

s = Son()
[Link]()
Constructor with super( ) Method
If we write constructor in the both classes, parent class and child class then the
parent class constructor is not available to the child class.
In this case only child class constructor is accessible which means child class
constructor is replacing parent class constructor.
super ( ) method is used to call parent class constructor or methods from the child
class.
Multi-level Inheritance
In multi-level inheritance, the class inherits the feature of another derived class
(Child Class).
object

Father Parent Class

Son Child Class

GrandSon GrandChild Class


Syntax:- object
class ParentClassName(object):
members of Parent Class
Parent Class
class ChildClassName(ParentClassName):
members of Child Class
Child Class
class GrandChildClassName(ChildClassName):
members of Grand Child Class
Grand Child
object

class Father (object):


members of class Father Parent Class Father

class Son (Father):


Child Class Son
members of class Son

class GrandSon (Son):


GrandChild Class GrandSon
members of class GrandSon
Hierarchical Inheritance
object

Father Parent Class

Son Daughter Son

Child Class
Syntax:-
class ParentClassName(object): object
members of Parent Class

Parent Class
class ChildClassName1(ParentClassName):
members of Child Class 2

class ChildClassName2(ParentClassName): Child Class 1 Child Class 2


members of Child Class 2
object
class Father (object):
members of class Father Parent Class

Father
class Son (Father):
Child Class
members of class Son
Son Daughter
class Daughter (Father):
Child Class
members of class Daughter
Multiple Inheritance
If a class is derived from more than one parent class, then it is called multiple
inheritance.
object

Parent Class Parent 1 Parent 2 Parent Class

Child Child Class


Syntax:- object
class ParentClassName1(object):
members of Parent Class

Parent 1 Parent 2
class ParentClassName2(object):
members of Parent Class

Child
class ChildClassName(ParentClassName1, ParentClassName2):
members of Child Class
object
class Father (object):
members of class Father Parent Class
Father Mother
class Mother (object):
Parent Class
members of class Mother
Son

class Son (Father, Mother):


Child Class
members of class Son
Method Resolution Order (MRO)
In the multiple inheritance scenario members of class are searched first in the
current class. If not found, the search continues into parent classes in depth-
first, left to right manner without searching the same class twice.
• Search for the child class before going to its parent class.
• When a class is inherited from several classes, it searches in the order from
left to right in the parent classes.
• It will not visit any class more than once which means a class in the
inheritance hierarchy is traversed only once exactly.
Method Resolution Order (MRO)
s = Son()
• The search will start from Son. As the object of Son is
created, the constructor of Son is called. object
• Son has super().__init__() inside his constructor so its
parent class, the one in the left side ‘Father’ class’s
constructor is called.
• Father class also has super().__init__() inside his
Father Mother
constructor so its parent ‘object’ class’s constructor is
called.
• Object does not have any constructor so the search will
continue down to right hand side class (Mother) of object Son
class so Mother class’s constructor is called.
• As Mother class also has super().__inti__() so its parent
class ‘object’ constructor is called but as object class
already visited, the search will stop here.
Polymorphism
Polymorphism is a word that came from two greek words, poly means many
and morphos means forms.
If a variable, object or method perform different behavior according to
situation, it is called polymorphism.
• Duck Typing
• Operator Overloading
• Method Overloading
• Method Overriding
Duck Typing
In Python, we follow a principle - If ‘it walks like a duck and talks like a duck,
it must be a duck’ which means python doesn’t care about which class of
object it is, if it is an object and required behavior is present for that object
then it will work. The type of object is distinguished only at runtime. This is
called as duck typing.
Duck Typing
Python doesn’t care about which class of object it is, in order to call an
existing method on an object. If the method is defined on the object, then it
will be called.

walk - thapak thapak walk – tabdak tabdak


Strong Typing
We can check whether the object passed to the method has the method being
invoked or not.
hasattr ( ) Function is used to check whether the object has a method or not.
Syntax:- hasattr(object, attribute)
Where attribute can be a method or variable. If it is found in the object then
this method returns True else False.
Method Overloading
When more than one method with the same name is defined in the same class,
it is known as method overloading.
In python, If a method is written such that it can perform more than one task, it
is called method overloading.
Method Overriding
If we write method in the both classes, parent class and child class then the parent
class’s method is not available to the child class.
In this case only child class’s method is accessible which means child class’s
method is replacing parent class’s method.
Method overriding is used when programmer want to modify the existing behavior
of a Method.
Method Overriding
class Add:
def result(self, a, b):
print(“Addition:”, a+b)

class Multi(Add):
def result(self, a, b):
print(“Multiplication:”, a*b)

m = Multi()
[Link](10, 20)
Method with super( ) Method
If we write method in the both classes, parent class and child class then the parent
class’s method is not available to the child class.
In this case only child class’s method is accessible which means child class’s
method is replacing parent class’s method.
super ( ) method is used to call parent class’s constructor or methods from the
child class.
Syntax:- super().methodName()
Operator Overloading
If any operator performs additional actions other than what it is meant for, it is
called operator overloading.
Module
A module is a file containing Python definitions and statements.
A module is a file containing group of variables, methods, function and classes etc.
They are executed only the first time the module name is encountered in an import
statement.
The file name is the module name with the suffix .py appended.
Ex:- [Link]

Type of Modules:-
• User-defined Modules
• Built-in Modules
Ex:- array, math, numpy, sys
When and Why use Module
Assume that you are building a very large project, it will be very difficult to manage all
logic within one single file so If you want to separate your similar logic to a separate
file, you can use module.
It will not only separate your logics but also help you to debug your code easily as you
know which logic is defined in which module.
When a module is developed, it can be reused in any program that needs that module.

Database [Link]

Calculation [Link]

Searching [Link]

[Link]
Creating a Module
Database [Link]

Calculation [Link]

Searching [Link]

[Link]

def add(a, b):


return a+b
def sub(a, b):
return a-b
[Link]
How to use Module
import statement is used to import modules.
Syntax:-
import module_name
import module_name as alias_name
from module_name import var_name,
class_name1,
var_name1,f_name,
class_name2,……,
class_name,
var_name2,……,
function_name1, method_name……,
class_nameN
var_nameN
function_name2,……, function_nameN
from module_name import f_name as alias_f_name
from module_name import *

Note - Modules can import other modules.


import module_name
This does not enter the names of the functions defined in module directly in the current
symbol table; it only enters the module name there.
Ex:- import cal

How to access Methods, Functions, Variable and Classes ?


Using the module name you can access the functions.
Syntax:- module_name.function_name()
Ex:-
[Link](10, 20) When 2 modules having same function name then
[Link](20, 10) This import module is good approach to use.
add = [Link]
add(10, 20)
import module_name as alias_name
This does not enter the names of the functions defined in module directly in the current
symbol table; it only enters the module name there. If the module name is followed by
as, then the name following as is bound directly to the imported module.
Ex:- import cal as c

How to access Methods, Functions, Variable and Classes ?


Using the alias_name you can access the functions.
Ex:-
[Link](10, 20)
[Link](20, 10)
add = [Link]
add(10, 20)
from module_name import function_name
There is a variant of the import statement that imports names from a module directly
into the importing module’s symbol table.
Ex:- from cal import add, sub

How to access Methods, Functions, Variable and Classes ?


You can access the functions directly by it’s name.
Ex:-
add(10, 20)
sub(20, 10)
from module_name import f_name as a_name
Ex:- from cal import add as s

How to access Methods, Functions, Variable and Classes ?


You can access the functions directly by it’s alias name.
Ex:-
s(10, 20)
from module_name import *
This imports all names except those beginning with an underscore (_).
Ex:- from cal import *

How to access Methods, Functions, Variable and Classes ?


You can access the functions directly by it’s name.
Ex:-
add(10, 20)
sub(20, 10)
Module Search Path
When a module named cal is imported, the interpreter first searches for a built-in
module with that name. If not found, it then searches for a file named [Link] in a list of
directories given by the variable [Link].
[Link] is initialized from these locations:
• Current Directory
• If not found then searches each directory in the Shell variable PYTHONPATH
• If not found then searches installation-dependent default path.

PYTHONPATH is a list of directory names, with the same syntax as the shell variable
PATH
Package
Packages are a way of structuring Python’s module namespace by using
“dotted module names”.
A package can have one or more modules which means, a package is
collection of modules and packages.
A package can contain packages.
Package is nothing but a Directory/Folder
Creating Package
Package is nothing but a Directory/Folder which MUST contain a special file
called __init__.py.
__init__.py file can be empty, it indicates that the directory it contains is a
Python package, so it can be imported the same way a module can be
imported.
SMS

Admin User Tech [Link] __init__.py

[Link] [Link] [Link]

[Link] [Link] [Link]

[Link] [Link] [Link]

[Link] __init__.py __init__.py

__init__.py
SMS

Admin User Tech [Link] __init__.py

Common [Link] [Link]

[Link] [Link] [Link]

[Link] [Link] [Link]

__init__.py __init__.py __init__.py

[Link] [Link] [Link] [Link] __init__.py


How to use Package
Syntax:- import [Link]
Syntax:- import [Link]
Ex:- import [Link]
Ex:- import [Link]

How to Access Variable, Function, Method, Class etc. ?


Syntax:- [Link]()
Syntax:- [Link]()
Ex:- [Link].admin_service( )
Ex:- [Link].admin_common_footer( )
How to use Package
Syntax:- from packageName import moduleName
Syntax:- from [Link] import moduleName
Ex:- from Admin import service
Ex:- from [Link] import footer

How to Access Variable, Function, Method, Class etc.


Syntax:- [Link]()
Ex:-
service.admin_service( )
footer.admin_common_footer( )
How to use Package
Syntax:- from [Link] import fun_name
Syntax:- from [Link] import fun_name
Ex:- from [Link] import admin_service
Ex:- from [Link] import admin_common_footer

How to Access Variable, Function, Method, Class etc.


Syntax:- functionName()
Ex:-
admin_service( )
admin_common_footer( )
How to use Package
Syntax:- from packageName import *
Syntax:- from [Link] import *
Ex:- from Admin import *
Ex:- from [Link] import *

How to Access Variable, Function, Method, Class etc.


Syntax:- [Link]()
Ex:-
service.admin_service( )
footer.admin_common_footer( )
__all__
if a package’s __init__.py code defines a list named __all__, it is taken to be
the list of module names that should be imported when from package import *
is encountered.
__all__ = [‘dashboard’, ‘service’, ‘product’]
Abstract Class
A class derived from ABC class which belongs to abc module, is known as abstract
class in Python.
ABC Class is known as Meta Class which means a class that defines the behavior of
other classes. So we can say, Meta Class ABC defines that the class which is derived
from it becomes an abstract class.
Abstract Class can have abstract method and concrete methods.
Abstract Class needs to be extended and its method implemented.
PVM can not create objects of an abstract class.
Ex:-
from abc import ABC, abstractmethod
Class Father(ABC):
Abstract Method
A abstract method is a method whose action is redefined in the child classes as
per the requirement of the object.
We can declare a method as abstract method by using @abstractmethod
decorator.
Ex:-
from abc import ABC, abstractmethod
Class Father(ABC):
@abstractmethod
def disp(self):
pass
Concrete Method
A Concrete method is a method whose action is defined in the abstract class
itself.
Ex:-
from abc import ABC, abstractmethod
Class Father(ABC):
@abstractmethod
def disp(self): Abstract Method / Method Without Body
pass
def show(self):
Concrete Method / Method with Body
print(“Concrete Method”)
Rules:
• PVM can not create objects of an abstract class.
• It is not necessary to declare all methods abstract in a abstract class.
• Abstract Class can have abstract method and concrete methods.
• If there is any abstract method in a class, that class must be abstract.
• The abstract methods of an abstract class must be defined in its child
class/subclass.
• If you are inheriting any abstract class that have abstract method, you must
either provide the implementation of the method or make this class abstract.
When use Abstract Class
We use abstract class when there are some common feature shared by all the
objects as they are.
Defence Force Gun is the common feature
Gun = AK 47 shared by all Forces but area
Area =
is different for them.

Army Air Force Navy


Gun = AK 47 Gun = AK 47 Gun = AK 47
Area = Land Area = Sky Area = Sea
Interface
In Python, The interface concept is not explicitly available, like available in
other languages e.g. Java.
In Python, an interface is an abstract class which contains only abstract method
but not a single concrete method.
Interface
from abc import ABC, abstractmethod
class Father(ABC):
@abstractmethod
def disp(self):
pass
def show(self):
print(“Concrete Method”)
Rules
All methods of an interface is abstract.
We can not create object of interface.
If a class is implementing an interface it has to define all the methods given in
that interface.
If a class does not implement all the methods declared in the interface, the
class must be declared abstract.
When use Interface
We use interface when all the features need to be implemented differently for
different objects.
Defence Force
Gun =
Area =

Army Air Force Navy


Gun = AK 41 Gun = AK 42 Gun = AK 43
Area = Land Area = Sky Area = Sea
Abstract Class vs Interface
• An abstract class can have abstract methods as well as concrete methods, but All
methods of an interface are abstract.
• We use abstract class when there are some common feature shared by all the objects
as they are while we use interface if all the feature need to be implemented
differently for different objects.
• Its programmer job to write child class for abstract class while in interface, any
third party vendor will take responsibility to write child class.
• Interfaces are slow when compared to abstract class.
Date and Time
Following modules are used to work with date, time, and duration.
• time
• datetime
• Epoch - The epoch is the point where the time starts, and is platform dependent.
This point is taken as the January 1st of the current year, 00:00:00. For Unix, the
epoch is January 1st 1970, 00:00:00 (UTC)

• UTC - UTC is Coordinated Universal Time (formerly known as Greenwich Mean


Time, or GMT). The acronym UTC is not a mistake but a compromise between
English and French.

• DST - DST is Daylight Saving Time, an adjustment of the timezone by (usually)


one hour during part of the year. DST rules are magic (determined by local law) and
can change from year to year.
Time Modules
• time ( ) Function – This function return the time in seconds since the epoch as a
floating point number. The specific date of the epoch and the handling of leap
seconds is platform dependent.

• ctime ( ) Function – This function is used to get current date and time. When we
pass epoch time in seconds to the function, it returns corresponding date and time in
string format. When we do not pass epoch time, it returns current date and time in
string format.
Time Modules
• localtime ( ) Function – This function is used to convert seconds into date and time. It returns an object
struct_time which can be used to access the attributes either using an index or using a name.
Index Attribute Value
0 tm_year 4 digit year number e.g. 2019
1 tm_mon Range [1, 12]
2 tm_mday Range [1, 31]
3 tm_hour Range [0, 23]
4 tm_min Range [0, 59]
5 tm_sec Range [0, 61], including leap seconds
6 tm_wday Range [0, 6], Monday is 0
7 tm_yday Range [1, 366]
8 tm_isdst [0, 1 or -1], 0 = no DST, 1 = DST is in effect, -1 = not known
tm_zone Timezone name
tm_gmtoff Offset east of UTC in seconds
datetime Module
datetime – It handles date and time. It has year, month, day, hour, minute, second,
microsecond and tzinfo attributes

date – It handles dates of gregorian calendar, without taking time zone into
consideration. It has year, month and day attributes.

time – It handles time assuming that every day has exactly 24 x 60 x 60 seconds. It has
hour, minute, second, microsecond and tzinfo attributes.

timedelta – It handles durations. The duration may be the difference between two date,
time or datetime instances.
datetime class
datetime object - A datetime object is a single object containing all the information from a date
object and a time object.
Creating Object of datetime Class
object_name = datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *,
fold=0)
The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The
remaining arguments may be integers, in the following ranges:
MINYEAR <= year <= MAXYEAR,
1 <= month <= 12,
1 <= day <= number of days in the given month and year,
0 <= hour < 24,
0 <= minute < 60,
0 <= second < 60, Ex:-
dt = datetime(year=2019, month=6, day=30, hour=5, minute=34)
0 <= microsecond < 1000000,
fold in [0, 1].
The fold parameter specifies whether there was any fold in time. A fold in time means a reverse back of the
clock time. In countries following Daylight Saving time during the end of summer clocks are reversed back by 1
hour. This reverse back is a fold in time.
* means a splat operator. Using a splat operator a tuple can be unpacked and a time object can be constructed
out of the values from the tuple.
datetime class’s Methods
now() – This method is used to get the current date and time. We can provide timezone
information to this method. If the timezone is not provided, then it takes the local time
zone. It returns an object that contains date and time information in any timezone. We
can use day, month, year, hour, minute and second.
Ex:- [Link]()

today() – This method is used to get the current date and time. It returns the date and
time information.
Ex:- [Link]()
date class
date object - A date object is an object containing information of year, month and day

Creating Object of date Class


object_name = date(year, month, day)
All arguments are required. Arguments may be integers, in the following ranges:
MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year
Ex:-
d = date(year=2019, month=6, day=30)
date class’s Method
today() Method – This method is used to get the current date. It returns only date.
Ex:- [Link]()
time class
time object - A time object is an object containing information of local time of day,
independent of any particular day, and subject to adjustment via a tzinfo object.
Creating Object of time Class
object_name = time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None,*,
fold=0)
All arguments are optional. tzinfo may be None, or an instance of a tzinfo subclass. The
remaining arguments may be integers, in the following ranges:
0 <= hour < 24,
0 <= minute < 60,
0 <= second < 60,
0 <= microsecond < 1000000,
fold in [0, 1].
All default to 0 except tzinfo, which defaults to None.
Ex:-
t = time(hour=5, minute=34, second=30)
timedelta class
timedelta object - A timedelta object represents a duration, the difference between two
dates or times.
It is possible to know the future dates or previous dates using timedelta.
Creating Object of timedelta Class
object_name = timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0,
hours=0, weeks=0)
All arguments are optional and default to 0. Arguments may be integers or floats, and may be
positive or negative.
Only days, seconds and microseconds are stored internally. Arguments are converted to those
units:
A millisecond is converted to 1000 microseconds.
A minute is converted to 60 seconds.
An hour is converted to 3600 seconds.
A week is converted to 7 days.
Ex:-
td = timedelta(days=10)
Comparing Two Dates
We can compare date class and datetime class objects using ==, <, >.
The comparison will return either True or False.
d1 = date(year=2019, month=6, day=30)
d2 = date(year=2016, month=6, day=30)
d1 == d2
d1 < d2
d1 > d2
Formatting Date and Time
strftime() Method – This method is used to format the content of datetime, date
and time class object. strftime represents string format to time. This method
convert the object into a specified format and returns the formatted string.
Ex:-
dt = [Link]()
newdt = [Link](“%B, %d, %Y”)

Format Code
Format Code
Format Code Meaning Example
%a Weekday in short name Sun, Mon,…., Sat
%A Weekday in full name Sunday, Monday,…, Saturday
%d Day of month with 0 padded 01, 02,….,30, 31
%b Month in short Name Jan, Feb, ……, Dec
%B Month in full Name January,….., December
%m Month in number with 0 padded 01, 02, …., 12
%y Year in short with 0 padded, without century 00, 01, 02,…., 99
%Y Year in Full with century 0001, 0002, ….., 9999
Format Code
Format Code Meaning Example
%H Hours with 0 padded (24 hours clock) 00, 01, 02,……, 23
%I Hours with 0 padded (12 hours clock) 01, 02,…., 12
%p AM/PM AM, PM
%M Minute with 0 padded 00, 01, ….., 59
%S Second with 0 padded 00, 01, ….., 59
%f Microsecond with 0 padded 000000,……, 999999
%Z Time zone name (empty), UTC, CST, EST
%j Day number of year with 0 padded 001, 002,……, 366
%U Week number of the year, Sunday as the first 00, 01, ……., 53
day of week with 0 padded
Format Code
Format Code Meaning Example
%c Locale’s appropriate date and time Tue Jan 30 21:30:00 2019
representation
%x Locale’s appropriate date representation 08/16/88 (None);
08/16/1988 (en_US);
16.08.1988 (de_DE)
%X Locale’s appropriate time representation 21:30:00 (en_US);
21:30:00 (de_DE)
%% A literal ‘%’ character %
[Link]
Multitasking
Executing multiple task at the same time.
Type of Multitasking
• Process based Multitasking
• Thread based Multitasking
Process Based Multitasking
Executing multiple task at the same time where each task is a
separate independent program(process), is called process based
multitasking. It is suitable for Operating System level.
Thread Based Multitasking
Executing multiple task at the same time where each task is a
separate independent part of the same program(process), is called
Thread based multitasking and each independent part is called
Thread. It is suitable for Programmatic level.
Ex: - MS Word
Thread
Thread is a separate flow of execution. Every thread has a task.
• Flying Thread
• CallAuntyMay Thread
• Watching MJ Thread
• Doc Thread
Multithreading
Using Multiple Threads in program or process

The main important application areas of multi threading are:


• Multimedia Graphic
• Animations
• Video Games
• Web Servers
• Application Servers
Main Thread
• When we start any Python Program, one thread begins running
immediately, which is called Main Thread of that program created by
PVM.
• The main thread is created automatically when your program is started.

import threading
t = threading.current_thread().getName()
print(t)
Creating a Thread
Thread class of threading module is used to create threads. To create our own
thread we need to create an object of Thread Class.
Following are the ways of creating threads:-
• Creating a thread without using a class
• Creating a thread by creating a child class to Thread class
• Creating a thread without creating child class to Thread class
Creating a thread without using a class
from threading import Thread
thread_object = Thread(target=function_name, args=(arg1, arg2, …))
thread_object – It represents our thread.
target – It represents the function on which the thread will act.
args – It represents a tuple of arguments which are passed to the function.
Ex:-
t = Thread(target=disp, args=(10,20))
How to Start Thread
Once a thread is created it should be started by calling start() Method.
from threading import Thread
def disp(a, b):
print(“Thread Running:”, a, b)
t = Thread(target=disp, args=(10, 20))
[Link]() Starting Thread

from threading import Thread


def disp(a, b):
print(“Thread Running:”, a, b)
for i in range(5):
t = Thread(target=disp, args=(10, 20))
[Link]() Starting Thread
from threading import Thread
Main thread is responsible to create and Start
def disp(): Child Thread, once the child thread has started
for i in range(5): both the thread behave separately.
print(“Child Thread”)
t = Thread(target=disp)
# upto here there is only one thread – Main Thread
# All the above code executed within Main Thread
[Link]()
# Once we start Child thread, there are now Two Threads – Main Thread and Thread-1
# Child Thread is responsible to run disp method
# and below code will be run by Main thread
for i in range(5):
print(“Main Thread”)
Set and Get Thread Name
• current_thread() – This function return current thread object.
• getName() – Every thread has a name by default, to get the name of thread
we can use this method.
• setName(name) – This method is used to set the name of thread.
• name Property – This property is used to get or set name of the thread.
Ex:-
thread_object.name = ‘String’
print(thread_object.name)
Creating a thread by creating a child class to Thread class
We can create our own thread child class by inheriting Thread Class from threading
module.
class ChildClassName(Thread):
statements
Thread_object = ChildClassName ()

Ex:-
class Mythread(Thread):
pass

t = Mythread()
Thread Class’s Methods
• start ( ) – Once a thread is created it should be started by calling start()
Method.
• run( ) – Every thread will run this method when thread is started. We can
override this method and write our own code as body of the method. A
thread will terminate automatically when it comes out of the run( ) Method.
• join ( ) – This method is used to wait till the thread completely executes the
run ( ) method.
Thread Child Class with Constructor
from threading import *
Thread Class as Parent Class

Class Mythread(Thread):
Calling Thread Class Constructor
def __init__(self, a):
Thread.__init__(self)
self.a = a

t = Mythread(10)
Creating a thread w/o creating a child class to Thread class
We can create an independent thread child class that does not inherit from Thread Class
from threading module.
class ClassName:
statements
object_name = ClassName ()
Thread_object = Thread(target=object_name.function_name, args=(arg1, arg2,…))
Ex:-
class Mythread:
def disp (self, a, b): print(a, b)
myt = Mythread()
t = Thread(target=[Link], args=(10, 20))
[Link]()
Single Tasking using a Thread
When multiple tasks are executed by a thread one by one, then it called single
tasking.
Writing Examination
• Question 1
• Question 2
• Question 3
Multitasking using Multiple Thread
When multiple tasks are executed at a time, then it is called Multi-tasking. For
this purpose we need more than one thread and when we use more than one
thread, it is called multi threading.
Multitasking using a Multiple Thread
When multiple tasks are executed at a time, then it is called Multi-tasking. For
this purpose we need more than one thread and when we use more than one
thread, it is called multi threading.
Race Condition
Race condition is a situation that occurs when threads are acting
in an unexpected sequence, thus leading to unreliable output.
This can be eliminated using thread synchronization.
Thread Identification Number
Every thread has an unique identification number which can be
accessed using variable ident.
Syntax:- Thread_object.ident
Ex:- [Link]
Thread Synchronization
Many threads trying to access the same object can lead to problems like making data
inconsistent or getting unexpected output So When a thread is already accessing an
object, preventing any other thread accessing the same object is called Thread
Synchronization.
The object on which the threads are synchronized is called Synchronized Object or
Mutually Exclusive Lock(mutex).
Thread Synchronization is recommended when multiple threads are acting on the same
object simultaneously.
There are following techniques to do Thread Synchronization:
• Using Locks
• Using RLock (Re-Entrant Lock)
• Using Semaphores
Locks
Locks are typically used to synchronize access to a shared resource. Lock can be used to lock the
object in which the thread is acting. A Lock has only two states, locked and unlocked. It is created
in the unlocked state.
acquire( )
This method is used to changes the state to locked and returns immediately. When the state is
locked, acquire() blocks until a call to release() in another thread changes it to unlocked, then the
acquire() call resets it to locked and returns.
Syntax:- acquire(blocking=True, timeout = -1)
• True – It blocks until the lock is unlocked, then set it to locked and return True.
• False - It does not block. If a call with blocking set to True would block, return False
immediately; otherwise, set the lock to locked and return True.
• Timeout - When invoked with the floating-point timeout argument set to a positive value,
block for at most the number of seconds specified by timeout and as long as the lock cannot
be acquired. A timeout argument of -1 specifies an unbounded wait. It is forbidden to specify
a timeout when blocking is false.
• The return value is True if the lock is acquired successfully, False if not (for example if the
timeout expired).
release( )
This method is used to release a lock. This can be called from any thread, not
only the thread which has acquired the lock.
When the lock is locked, reset it to unlocked, and return. If any other threads
are blocked waiting for the lock to become unlocked, allow exactly one of
them to proceed.
When invoked on an unlocked lock, a RuntimeError is raised.
There is no return value.
Syntax:- release( )
RLock
A reentrant lock is a synchronization primitive that may be acquired multiple times by the same
thread.
The standard Lock doesn’t know which thread is currently holding the lock. If the lock is held,
any thread that attempts to acquire it will block, even if the same thread itself is already holding
the lock. In such cases, RLock (re-entrant lock) is used.
A reentrant lock must be released by the thread that acquired it. Once a thread has acquired a
reentrant lock, the same thread may acquire it again without blocking; the thread must release it
once for each time it has acquired it.
Semaphore
This is one of the oldest synchronization primitives in the history of computer science, invented
by the early Dutch computer scientist Edsger W. Dijkstra,
A semaphore manages an internal counter which is decremented by each acquire() call and
incremented by each release() call.
The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until
some other thread calls release().
It’s usually better to use the BoundedSemaphore class, which considers it to be an error to call
release more often than you’ve called acquire.
Dead Lock
A Deadlock is a situation where each of the process waits for a resource which is being
assigned to some another process. In this situation, none of the process gets executed
since the resource it needs, is held by some other process which is also waiting for
some other resource to be released.

P1 Terrorist and army example

R2 R1

P2
Thread Communication
Two or more threads communicate with each other.
• Event
• Condition
• Queue
Event
This is one of the simplest mechanisms for communication between threads:
one thread signals an event and other threads wait for it.
An event object manages an internal flag that can be set to true with the set()
method and reset to false with the clear() method. The wait() method blocks
until the flag is true.
The flag is initially false.

Create Event Object


from threading import Event
e = Event()
Event Methods
set()- It sets the internal flag to true. All threads waiting for it to become true
are awakened. Threads that call wait() once the flag is true will not block at all.

clear()- It resets the internal flag to false. Subsequently, threads calling wait()
will block until set() is called to set the internal flag to true again.

is_set() – It returns true if and only if the internal flag is true.


Event Methods
wait(timeout=None) – It blocks until the internal flag is true. If the internal flag is true
on entry, return immediately. Otherwise, block until another thread calls set() to set the
flag to true, or until the optional timeout occurs.
When the timeout argument is present and not None, it should be a floating point
number specifying a timeout for the operation in seconds (or fractions thereof).
This method returns true if and only if the internal flag has been set to true, either
before the wait call or after the wait starts, so it will always return True except if a
timeout is given and the operation times out.
Condition
Condition class is used to improve speed of communication between Threads.
The condition class object is called condition variable.
A condition variable is always associated with some kind of lock; this can be
passed in or one will be created by default. Passing one in is useful when
several condition variables must share the same lock. The lock is part of the
condition object: you don’t have to track it separately.
A condition is a more advanced version of the event object.

Create Condition Object


from threading import Condition
cv = Condition()
Condition Method
• notify(n=1) – This method is used to immediately wake up one thread waiting on
the condition. Where n is number of thread need to wake up.

• notify_all() – This method is used to wake up all threads waiting on the condition.

• wait(timeout=None) – This method wait until notified or until a timeout occurs. If


the calling thread has not acquired the lock when this method is called, a
RuntimeError is raised. Wait terminates when invokes notify() method or
notify_all() method. The return value is True unless a given timeout expired, in
which case it is False.
Queue
The Queue class of queue module is useful to create a queue that holds the
data produced by the producer.
The data can be taken from the queue and utilized by the consumer.
We need not use locks since queues are thread safe.

Create Queue Object:


from queue import Queue
q = Queue()
Queue Methods
put ( ) – This method is used by Producer to insert items into the queue.
Syntax:- queue_object.put(item)
Ex:- [Link](i)

get ( ) – This method is used by Consumer to retrieve items from the queue.
Syntax:- producer_object.queue_object.get(item)
Ex:- [Link](i)

empty() – This method returns True if queue is Empty else returns False.
Ex:- [Link]()

full() – This method returns True if queue is Full else returns False.
Ex:- [Link]()
Daemon Thread
A daemon thread is a thread which runs continuously in the background.
It provides support to non-daemon threads.
When last non-daemon thread terminates, automatically all daemon threads
will be terminated. We are not required to terminate daemon thread explicitly.
Daemon Threads
Create Daemon Thread
setDaemon(True) Method or daemon = True Property is used to make a
thread a Daemon thread.
Ex:-
t1 = Thread(target=disp)
[Link](True)
[Link] = True
Method
setDaemon(True/False) - This method is used to set a thread as daemon thread.
You can set thread as daemon only before starting that thread which means active
thread status cannot be changed as daemon.
If we pass True non-daemon thread will become daemon and if False daemon thread
will become non-daemon.

daemon Property - This property is used to check whether a thread is daemon or not. It
returns True if thread is daemon else False.
We can also use daemon property to set a thread as daemon thread or vice versa.

isDaemon() - This method is used to check whether a thread is daemon or not. It returns
True if thread is daemon else False.
Default Nature of Thread
• Main Thread is always non-daemon thread.
• Rest of the threads inherits daemon nature from their parents.
– If parent thread is non daemon then child thread will become non daemon thread.
– If parent thread is daemon then child thread will also become a daemon thread.
• When last non-daemon thread terminates, automatically all daemon threads
will be terminated. We are not required to terminate daemon thread
explicitly.
Files
File is the collection of data that is available to a program. We can retrieve and
use data stored in a file whenever we required.

Advantages:-
• Stored Data is permanent unless someone remove it.
• Stored data can be shared.
• It is possible to update or remove the data.
Type of Files
There are two type of files:-
Text File – It stores data in the form of characters. It is used to store characters
and strings.

Binary File – It stores data in the form of bytes, a group of 8 bits each. It is
used to store text, images, pdf, csv, video and audio.
Text Mode and Binary Mode
Text Mode – A file opened in text mode, treats its contents as if it contains text
strings of the str type.
When you get data from a text mode file, Python first decodes the raw bytes
using either a platform-dependent encoding or, specified one.

Binary Mode – A file opened in Binary Mode, Python uses the data in the file
without any decoding, binary mode file reflects the raw data in the file.
Opening a File
If we want to use a file or its data, first we have to open it.
open( ) – Open ( ) function is used to open a file. It returns a pointer to the beginning of the file.
This is called file handler or file object.
Syntax:- open(‘filename’, mode='r', buffering, encoding=None, errors=None, newline=None,
closefd=True, opener=None)
• filename – It represents a name of a file.
• mode – It represents the purpose of opening the file. It defaults to 'r' which means open for
reading in text mode.
• buffering – It is an integer value used to set the size of the buffer for the file. In the binary
mode we can pass 0 as buffering integer to inform not to use any buffering. In text mode we
can pass 1 for buffering to retrieve data from the file one line at a time. We can pass any
positive integer. Default is 4096 or 8192 bytes.
Opening a File
Syntax:- open(‘filename’, mode='r', buffering, encoding=None, errors=None, newline=None,
closefd=True, opener=None)
• encoding – name of the encoding used to decode or encode the file. It should be used only in
text mode. Ex:- utf-8
• errors – an optional string that specifies how encoding and decoding errors are to be handled,
this cannot be used in binary mode. Some of the standard values are strict, ignore, replace etc.
• newline: this parameter controls how universal newlines mode works (it only applies to text
mode). It can be None, ”, ‘\n’, ‘\r’, and ‘\r\n’.
• closefd – If closefd is False and a file descriptor rather than a filename was given, the
underlying file descriptor will be kept open when the file is closed. If a filename is given
closefd must be True (the default) otherwise an error will be raised.
• opener: A custom opener can be used by passing a callable as opener.
Opening a File
File Name File Path

f = open(‘[Link]’, ‘w’) f = open(‘D:\\myfolder\\[Link]’, ‘w’)

File Handler/ File Mode


File object
Text File Mode
Character Meaning

r Open for reading. The file pointer is positioned at the beginning of the file. If the file doesn’t
exist it will show FileNotFoundError.
w Open for writing. If any data is already present in the file, it will overwrite the data. If the file
doesn’t exist it will create that file.
x Open for exclusive creation with write. The specified file must not be available, if the specified
file is available it will show error FileExistsError
a Open for appending. The file pointer is positioned at the end of the file. It appends new data at
the end of file. If the file does not exists it will create a new file for writing data.
r+ Open for reading and then writing

w+ Open for writing and then reading. It will overwrite existing data

a+ Open for appending then reading. It won't overwrite existing data


Binary File Mode
Character Meaning

rb Open for reading. The file pointer is positioned at the beginning of the file. If the file doesn’t
exist it will show FileNotFoundError.
wb Open for writing. If any data is already present in the file, it will overwrite the data. If the file
doesn’t exist it will create that file.
xb Open for exclusive creation with write. The specified file must not be available, if the specified
file is available it will show error FileExistsError
ab Open for appending. The file pointer is positioned at the end of the file. It appends new data at
the end of file. If the file does not exists it will create a new file for writing data.
rb+ Open for reading and then writing

wb+ Open for writing and then reading. It will overwrite existing data

ab+ Open for appending then reading. It won't overwrite existing data
Closing a File
close( ) – This method is used to close, opened file.
Once we close the file, file object is deleted from the memory hence file will be no
longer accessible unless we open it again.
If you don’t explicitly close a file, Python’s garbage collector will eventually destroy
the object and close the open file for you, but the file may stay open for a while so You
should always close opened file.

What will happened if we do not close opened file:-


• Data of the file may be corrupted or deleted.
• Memory utilized by the file is not freed it may cause of insufficient memory.
File object Variables
name – This shows the name of specified file.
Syntax:- file_object.name

mode – This shows mode (purpose) of the file.


Syntax:- file_object.mode

closed – This used to check whether file has closed or not.


It shows True if file is closed else shows False.
Syntax:- file_object.closed
File object Methods
readable() – This method is used to check whether file is readable or not.
It returns True if file is readable else returns False.
Syntax:- file_object.readable()

writable() – This method is used to check whether file is writable or not.


It returns True if file is writable else returns False.
Syntax:- file_object.writable()
Check File exists or not
isfile() – This method is used to check whether specified file is exists or not.
This method belongs to path module which is sub module of os module.
Syntax:-
import os
[Link](filename)
Writing Data to the file
write ( ) – This method is used to store/write character or string into the file
represented by the file object. It returns the number of character written.
Syntax:- file_object.write(string)

writelines ( ) – This method is used to store/write group of string (list, tuple,


set) into the file represented by the file object.
Syntax:- file_object.writelines(group of string)
Reading Data from file
read (size) – This method is used to read data/content from a file and returns it
as string in text mode or bytes object in binary mode.
Syntax:- file_object.read(size)
Where size represents the number of bytes to be read from the beginning of the
file.
When size is omitted or negative, the entire contents of the file will be read
and returned.
If the end of the file has been reached, file_object.read() will return an empty
string (‘’).
Reading Data from file
readline () – This method is used to read single line from a file.
Syntax:- file_object.readline()

readlines () – This method is used to read all lines from a file. It will return list
of line.
Syntax:- file_object.readlines()
Methods
tell ( ) - This method is used to find current position of file pointer from
beginning of the file. Position starts from 0.
Syntax:- file_object.tell()

seek(position) – This method is used to move file pointer from one position to
another position from beginning of the file. Position starts from 0 and it must
be positive integer.
Syntax:- file_object.seek(position)
with Statement
The with statement can be used while opening a file.
When we open a file using with statement there is no need to close the file
explicitly.
Syntax:-
with open (‘filename’, mode=‘r’) as file_object :
statements
Ex:-
with open(‘[Link]’) as f :
[Link]()
Pickling
Pickling is a process of converting a class object into a byte stream so that it
can be stored into a file. This is also called as object serialization.
We use pickle module to perform pickling and unpickling.
Function
dump( ) – This function is used to perform the pickling. It returns the pickled
representation of the object as a bytes object, instead of writing it to a file.
This method belongs to pickle module.
Syntax:-
import pickle
[Link](object, file)
Unpickling
Unpickling is a process whereby byte stream is converted back into a class
object. It is inverse operation of pickling. This is also called as de-serialization.
Pickling and unpickling should be done using binary files since they support
byte streams.
We use pickle module to perform pickling and unpickling.

Warning: The pickle module is not secure against erroneous or maliciously constructed
data. Never unpickle data received from an untrusted or unauthenticated source.
Function
load( ) – This function is used to read an pickled object from a binary file and
returns it into object. This method belongs to pickle module.
Syntax:-
import pickle
[Link](file)
Why do we need Pickling and Unpickling
When we store some structured data in the file and want to perform calculation
that time we need pickling and unpickling.

stu1 stu1
Pickling dump( ) load( ) Unpickling
stu2 stu2
Directory
os module – This module is used to perform simple operation on directories.
This module represents operating system dependent functionality.
import os
• getcwd() – This method is used to know the currently working directory.
Syntax:- [Link]()

• mkdir(‘dirname’) – This method is used to create a directory in the present


directory.
Syntax:- [Link](‘dirname’)

• mkdir(‘parentdirname/childdirname’) – This method is used to create a


child directory in the parent directory. Parent directory must be exist else it
will show error.
Syntax:- [Link](‘parentdirname/childdirname’)
• makedirs(‘parentdir/childdir/grandchilddir’) – This method is used to
recursively create sub directories.
Syntax:- [Link](‘parentdir/childdir/grandchilddir’)

• chdir(‘dirname’) – This method is used to change current working


directory.
Syntax:- [Link](‘dirname’)

• rename(‘oldname’, ‘newname’) – This method is used to change the


directory name.
Syntax:- [Link](‘oldname’, ‘newname’)
• rmdir(‘dirname’) – This method is used to remove a directory from the
current working directory. We can also specify path for directory.
Syntax:- [Link](‘dirname’), [Link](‘parentdirname/childdirname’)

• removedirs(‘dirname’) – This method is used to recursively remove all


directories.
Syntax:- [Link](‘parentdirname/childdirname’)

• walk() – This method is used to know contents of a directory including sub


directory. It returns an iterator object whose contents can be displayed
using for loop. This iterator object contains directory path, directoryname,
filename found in the specified directory.
Syntax:- [Link](path, topdown=True, onerror=None, followlinks=False)
• path – It represents the directory name. we can write dot (.) to specify current
directory.
• topdown – If it is True the directory and its sub directories are traversed in top-
down manner. If it is False then the directory and its sub directories are
traversed in bottom-up manner.
• onerror – It represents what to do when an error is detected. We can give a
function.
• followlinks – True to visit directories pointed to by symbolic links, on system
that support them. If False walk() will not walk down into symbolic links that
resolve to directories.
Database
Database is integrated collection of related information along with the details
so that it is available to the several user for the different application.

Database Name
Row or Record or Tuple Entity Student
Table Name: Computer Science Column or Field or Attributes

Roll Number Name Address Fees


1 Rahul Delhi 10000
2 Raj Mumbai 5000
3 Rohit Kolkata 15000

DATABASE
Table Name: Users
user_id password
Sam12 Xyz
Rony23 Zxy
John90 Qwerty
James iuytr23
Table Name: Pages
page_name likes
Geeky Shows 3000
Etc 100000
Other 5000000
Python Supports various Databases
• MySQL
• MS-SQL
• SQLite
• MongoDB
• Oracle OCI8
• PostgreSQL
• Firebird
• MS Access
MySQL
MySQL is an open source database management system
application which will help us to manage the database like store
and retrieve data.
CRUD
• Create
• Read
• Update
• Delete
Requirements
• SQL – To write sql queries.

• MySQL – We have to install MySQL in our system. It is an open source database


management system application which will help us to manage the database like
store and retrieve data. We have to set the path variable to bin directory of MySQL
server.

• Connector or Driver – A connector is a program that establishes connection


between Python programs and MySQL database without installing connector it is
not possible make communication between python program and MySQL database.
MySQL
It is an open source database management system application which will help
us to manage the database like store and retrieve data.
To work with MySQL in Python program we have to import connector sub
module of mysql module.
import [Link]
Creating Connection
connect() – This method is used to open or establish a new connection. It returns an
object representing the connection.
Syntax: -
connection_object = connect(user=‘username’, password=‘pass’ host=‘localhost’,
port=3306);
eg: -
import [Link]
conn = [Link](user=‘root’, password=‘geek’, host=‘localhost’,
port=3306)
Creating Connection
import [Link]
config = {
‘user’: ‘root’,
‘password’: ‘geek’,
‘host’ : ‘localhost’,
‘port’: 3306
}
conn = [Link](**config)
Check Connection
is_connected() – This method is used to check if the connection to MySQL is
established or not. It returns True if the connection is established successfully.
Syntax:- connection_object.is_connected()
eg:-
import [Link]
conn = [Link](user=‘root’, password=‘geek’,
host=‘localhost’)
print(conn.is_connected())
Close Connection
close() – This method is used to close the connection.
Syntax:- connection_object.close()
eg:-
import [Link]
conn = [Link](user=‘root’, password=‘geek’,
host=‘localhost’)
# Do your work
[Link]()
Operations
• Create Database
• Show Database
cursor() Method
This method is used to create cursor class object.
We need cursor object so we can call execute() method.
Syntax:- cursor_object = connection_object.cursor()
Arguments may be passed to the cursor() method to control what type of cursor to
create:
• If buffered is True, the cursor fetches all rows from the server after an operation is
executed. This is useful when queries return small result sets. buffered can be used
alone, or in combination with the dictionary or named_tuple argument.
• If dictionary is True, the cursor returns rows as dictionaries.
• If named_tuple is True, the cursor returns rows as named tuples.
• If prepared is True, the cursor is used for executing prepared statements.
cursor() Method
• if raw is True, the cursor skips the conversion from MySQL data types to Python
types when fetching rows. A raw cursor is usually used to get better performance or
when you want to do the conversion yourself.
• The cursor_class argument can be used to pass a class to use for instantiating a new
cursor. It must be a subclass of [Link].

The returned object depends on the combination of the arguments. Examples:


• If not buffered and not raw: MySQLCursor
• If buffered and not raw: MySQLCursorBuffered
• If not buffered and raw: MySQLCursorRaw
• If buffered and raw: MySQLCursorBufferedRaw
cursor() Method
The returned object depends on the combination of the arguments. Examples:
• If not buffered and not raw: MySQLCursor
• If buffered and not raw: MySQLCursorBuffered
• If not buffered and raw: MySQLCursorRaw
• If buffered and raw: MySQLCursorBufferedRaw

eg:- myc = [Link]() MySQLCursor

eg:- myc = [Link](buffered=True) MySQLCursorBuffered

eg:- myc = [Link](prepared=True) MySQLCursorPrepared


execute() Method
This method is used to execute given SQL queries.
We need cursor object so we can call execute() method.
Syntax:- cursor_object.execute(sql, param=None, multi=False)
Sql – It is sql query.
Param – The parameters found in the tuple or dictionary params are bound to the variables in the
operation.
Multi – execute() returns an iterator if multi is True.
eg:-
myc = [Link]()
[Link](‘SELECT * FROM student’)

sql =‘SELECT * FROM student’


myc = [Link]()
[Link](sql)
Close Cursor
close () method closes the cursor, resets all results, and ensures that the cursor
object has no reference to its original connection object.
Syntax:- cursor_object.close()
eg:- [Link]()
Connecting to Database
connect() – This method is used to open or establish a new connection. It returns an
object representing the connection.
Syntax: -
connection_object = connect(user=‘username’, password=‘pass’, database=‘dbname’,
host=‘localhost’, port=3306);
eg: -
import [Link]
conn = [Link](user=‘root’, password=‘geek’, host=‘localhost’,
database=‘pdb’, port=3306)
Connecting to Database
import [Link]
config = {
‘user’: ‘root’,
‘password’: ‘geek’,
‘host’ : ‘localhost’,
‘database’ : ‘pdb’,
‘port’: 3307
}
conn = [Link](**config)
executemany() Method
This method is used to execute given SQL query against all parameter sequences or
mappings found in the sequence seq_of_params.
With the executemany() method, it is not possible to specify multiple statements to
execute in the operation argument.
Syntax:- cursor_object.executemany(sql, seq_of_param)
eg:-
myc = [Link]()
[Link](sql, seq_of_params)
Operations
• Create Table
• Show Table
• Insert Data
• Delete Data
• Update Data
commit() Method
This method is used to save inserted row in the table. It is required to make the
changes, otherwise no changes are made to the table.
This method sends a COMMIT statement to the MySQL server, committing
the current transaction. Since by default Connector/Python does not
autocommit, it is important to call this method after every transaction that
modifies data for tables that use transactional storage engines.
Syntax:- connection_object.commit()
eg:- [Link]()
rollback() Method
This method is used to un-save row, if there is an error.
This method sends a ROLLBACK statement to the MySQL server, undoing all data changes from
the current transaction. By default, Connector/Python does not autocommit, so it is possible to
cancel transactions when using transactional storage engines such as InnoDB.
Syntax:- connection_object.rollback()
eg:- [Link]()

try:
[Link](sql)
[Link]()
except:
[Link]()
rowcount Property
This read-only property returns the number of rows returned for SELECT
statements, or the number of rows affected by DML statements such as
INSERT or UPDATE.
Syntax:- cursor_object.rowcount
eg:- [Link]
lastrowid Property
This read-only property returns the value generated for an AUTO_INCREMENT
column by the previous INSERT or UPDATE statement or None when there is no such
value available.
If you perform an INSERT into a table that contains an AUTO_INCREMENT column,
lastrowid returns the AUTO_INCREMENT value for the new row.
If you insert multiple rows into a table using a single INSERT statement, the lastrowid
property contains the last insert id of the first row.
Syntax:- cursor_object.lastrowid
eg:- [Link]
fetchone() Method
This method retrieves the next row of a query result set and returns a single
sequence, or None if no more rows are available. By default, the returned tuple
consists of data returned by the MySQL server, converted to Python objects. If
the cursor is a raw cursor, no such conversion occurs.
You must fetch all rows for the current query before executing new statements
using the same connection.
Syntax:- row = cursor_object.fetchone()
eg:- row = [Link]()
fetchall() Method
This method fetches all (or all remaining) rows of a query result set and returns
a list of tuples. If no more rows are available, it returns an empty list.
You must fetch all rows for the current query before executing new statements
using the same connection.
Syntax:- rows = cursor_object.fetchall()
eg:- rows = [Link]()
fetchmany() Method
This method fetches the next set of rows of a query result and returns a list of
tuples. If no more rows are available, it returns an empty list.
The number of rows returned can be specified using the size argument, which
defaults to one. Fewer rows are returned if fewer rows are available than
specified.
You must fetch all rows for the current query before executing new statements
using the same connection.
Syntax:- rows = cursor_object.fetchmany(size=1)
eg:- rows = [Link](3)
Parameterized Query
A parameterized query is a query which can use the format or pyformat
parameterization style for parameters and the parameter values supplied at
execution.
These executed with MySQLCursor can use the %s and %(key)s format style.
%s is used as format style in the sql queries, while using tuple parameters.
%(key)s is used as format style in the sql queries, while using dictionary
parameters.

myc = [Link]()
Tuple Parameters
sql = 'INSERT INTO student(name, roll, fees) VALUES(%s, %s, %s)‘
myc = [Link]()
[Link](sql, ("Rohan", 111, 60000.50))

sql = 'INSERT INTO student(name, roll, fees) VALUES(%s, %s, %s)'


myc = [Link]()
params = ("Rohan", 111, 60000.50)
[Link](sql, params)
Dictionary Parameters
sql = 'INSERT INTO student(name, roll, fees) VALUES(%(name)s, %(roll)s,
%(fees)s)‘
myc = [Link]()
[Link](sql, {'name':'Kajal', 'roll':777, 'fees': 54100})

sql = 'INSERT INTO student(name, roll, fees) VALUES(%(name)s, %(roll)s,


%(fees)s)‘
myc = [Link]()
params = {'name':'Kajal', 'roll':777, 'fees': 54100}
[Link](sql, params)
executemany() Method
This method is used to prepare given SQL query and executes it against all
parameter sequences or mappings found in the sequence seq_of_params.
With the executemany() method, it is not possible to specify multiple
statements to execute in the sql argument.
Syntax:- cursor_object.executemany(sql, seq_of_params)
sql – It is sql qrery
seq_of_params – It is a list of tuples, containing the data to insert.
Prepared Statement
A prepared statement is used to execute the same statement repeatedly with high
efficiency. The prepared statement execution consists of two stages: prepare and
execute.
At the prepare stage a statement template is sent to the database server. The server
performs a syntax check and initializes server internal resources for later use.
At the Execute Stage the parameter values are sent to the server. The server creates a
statement from the statement template and these values to execute it.
Prepared statements executed with MySQLCursorPrepared can use the format %s or
qmark ? parameterization style.
%s and ? are called as parameter marker.
This differs from nonprepared statements executed with MySQLCursor, which can use
the format or pyformat parameterization style.
Advantage
• Prepared statements are very useful against SQL injections.
• Prepared statements reduce parsing time as the preparation on the query is
done only once (although the statement is executed multiple times)
Creating a Cursor
Using prepared=True argument to the cursor() method, creates a cursor that
enables execution of prepared statements using the binary protocol.
In this case, the cursor() method of the connection object returns a
MySQLCursorPrepared object.
e.g:-
myc = [Link](prepared=True)
sql = 'INSERT INTO student(name, roll, fees) VALUES(%s, %s, %s)‘
myc = [Link](prepared=True)
[Link](sql, ("Rohan", 111, 60000.50))

sql = 'INSERT INTO student(name, roll, fees) VALUES(%s, %s, %s)'


myc = [Link](prepared=True)
params = ("Rohan", 111, 60000.50)
[Link](sql, params)
sql = 'INSERT INTO student(name, roll, fees) VALUES(?, ?, ?)‘
myc = [Link](prepared=True)
[Link](sql, ("Rohan", 111, 60000.50))

sql = 'INSERT INTO student(name, roll, fees) VALUES(?, ?, ?)'


myc = [Link](prepared=True)
params = ("Rohan", 111, 60000.50)
[Link](sql, params)
How it works
• For the first call to the execute() method, the cursor prepares the statement.
If data is given in the same call, it also executes the statement and you
should fetch the data.
• For subsequent execute() calls that pass the same SQL statement, the cursor
skips the preparation phase.
Exception
An exception is a runtime error which can be handled by the programmer.
All exceptions are represented as classes in Python.

Type of Exception:-
• Built-in Exception – Exceptions which are already available in Python
Language. The base class for all built-in exceptions is BaseException class.
• User Defined Exception – A programmer can create his own exceptions,
called user-defined exceptions.
All exceptions are represented as classes in Python.

BaseException

Exception

StandardError Warning

ArthmeticError AssertionError SyntaxError TypeError EOFError RuntimeError ImportError NameError DeprecationWarning RuntimeWarning ImportWarning
Need of Exception Handling
• When an exception occurs, the program terminates suddenly.
• Suddenly termination of program may corrupt the program.
• Exception may cause data loss from the database or a file.
Exception Handling
Try – The try block contains code which may cause exceptions.
Syntax-
try:
statements

Except – The except block is used to catch an exception that is raised in the try block. There can
be multiple except block for try block.
Syntax-
except ExceptionName:
statements
Exception Handling
Else – This block will get executed when no exception is raised. Else block is executed after try
block.
Syntax-
else:
statements

Finally – This block will get executed irrespective of whether there is an exception or not.
Syntax-
finally:
statements
• We can write several except blocks for a single try block.
• We can write multiple except blocks to handle multiple exceptions.
• We can write try block without any except blocks.
• We can not write except block without a try block.
• Finally block is always executed irrespective of whether there is an
exception or not.
• Else block is optional.
• Finally block is optional.
try: try:
Statement Statement
except ExceptionClassName: except ExceptionClassName1:
Statement Statement
else: except ExceptionClassName2:
Statement Statement
finally: finally:
Statement Statement

try: try:
Statement Statement
except ExceptionClassName:
Statement except ExceptionClassName:
Statement
Except
• With the Exception Class Name
except ExceptionClassName:
Statement

• Exception as an object
except ExceptionClassName as obj:
Statement

• Multiple Exception within tuple


except (ExceptionClassName1, ExceptionClassName2, ExceptionClassName3, …… ):
Statement

• Catch any Type of Exception


except:
Statement
Assert Statement
The assert Statement is useful to ensure that a given condition is True. If it is
not true, it raises AssertionError.
Syntax:- assert condition, error_message
• If the condition is False then the exception by the name AssertionError is
raised along with the message.
• If message is not given and the condition is False then also AssertionError
is raised without message.
User Defined Exception
A programmer can create his own exceptions, called user-defined exceptions
or Custom Exception.
• Creating Exception Class using Exception Class as a Base Class
• Raising Exception
• Handling Exception
Creating Exception
We can create our own exception by creating a sub class to built-in Exception
class.
class MyException(Exception):
pass

class MyException(Exception):
def __init__(self, arg):
[Link] = arg
Raising Exception
raise statement is used to raise the user defined exception.
raise MyException(‘message’)
Handling Exception
Using try and except block Programmer can handle exceptions.

try:
statement
except MyException as mye:
statement
Error vs Exception
• An exception is an error that can be handled by a programmer.
• An exception which are not handled by programmer, becomes an error.
• All exceptions occur only at runtime.
• Error may occur at compile time or runtime.
Error vs Warning
It is compulsory to handle all error otherwise program will not
execute, while warning represents a caution and even though it is
not handled, the program will execute.
Errors are derived as sub class of StandardError, while warning
derived as sub class from Warning class.
Logging
Logging is useful to track the error or exception
or information. It also helps in debugging.
We use Logging Module to log the error.
Syntax:-
import logging
from logging import *
basicConfig (**kwargs) Method
This method is used to config the logging System.
Syntax:-
basicConfig(**kwargs)
• filename – It specifies that a FileHandler be created, using the specified
filename, rather than a StreamHandler.
• filemode - If filename is specified, open the file in this mode. Defaults to 'a’. We
can write ‘w’
• level - Set the root logger level to the specified level.
• format - Use the specified format string for the handler.
• datefmt - Use the specified date/time format, as accepted by [Link]().
• style - If format is specified, use this style for the format string. One of '%', '{'
or '$' for printf-style, [Link]() or [Link] respectively. Defaults to
'%’.
basicConfig (**kwargs) Method
This method is used to config the logging System.
Syntax:-
basicConfig(**kwargs)
• stream – Use the specified stream to initialize the StreamHandler. Note that this
argument is incompatible with filename - if both are present, a ValueError is
raised.
• handlers – If specified, this should be an iterable of already created handlers to
add to the root logger. Any handlers which don’t already have a formatter set
will be assigned the default formatter created in this function. Note that this
argument is incompatible with filename or stream - if both are present, a
ValueError is raised.
• force - If this keyword argument is specified as true, any existing handlers
attached to the root logger are removed and closed, before carrying out the
configuration as specified by the other arguments.
Levels
Level Numeric Value
NOTSET 0
DEBUG 10
INFO 20
WARNING 30
ERROR 40
CRITICAL 50
Methods
• getLogger() – This method returns a logger with the specified name or, if name is None, return a
logger which is the root logger of the hierarchy. If specified, the name is typically a dot-
separated hierarchical name like ‘a’, ‘a.b’ or ‘a.b.c.d’.

• info(msg) - This will log a message with level INFO on this logger.

• warning(msg) - This will log a message with level WARNING on this logger.

• error(msg) - This will log a message with level ERROR on this logger.

• critical(msg) - This will log a message with level CRITICAL on this logger.

• exception(msg) - This will log a message with level ERROR on this logger.
Format
Format can take a string with LogRecord attributes in any arrangement you like.
asctime – Human-readable time when the LogRecord was created. By default this is
of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are
millisecond portion of the time).
Ex:- %(asctime)s

created – Time when the LogRecord was created (as returned by [Link]()).
Ex:- %(created)f

filename – Filename portion of pathname.


Ex:- %(filename)s
LogRecord Attributes
levelname – Text logging level for the message ('DEBUG', 'INFO', 'WARNING',
'ERROR', 'CRITICAL’).
Ex:- %(levelname)s

levelno – Numeric logging level for the message (DEBUG, INFO, WARNING,
ERROR, CRITICAL).
Ex:- %(levelno)s

lineno – Source line number where the logging call was issued (if available).
Ex:- %(lineno)d
LogRecord Attributes
message – The logged message, computed as msg % args. This is set when
[Link]() is invoked.
Ex:- %(message)s

name – Name of the logger used to log the call.


Ex:- %(name)s

pathname – Full pathname of the source file where the logging call was issued (if
available).
Ex:- %(pathname)s
LogRecord Attributes
args
exc_info
funcname
module
msecs
msg
process
processname
relativecreated
stack_info
thread
threadname
What Next ?
• Update Yourself
• Build Application
• Framework/Library – Django, Flask, Skulpt, Brython, Tkinter,
SciPy, Pandas, TensorFlow, Kivy etc.

You might also like