Adavance Python
Adavance Python
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
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):
print([Link]) [Link] = ‘RealMe X’
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
realme = Mobile( )
• 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
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
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
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:
• Multi-level Inheritance
• Hierarchical Inheritance
• Multiple Inheritance
Declaration of Child Class
class ChildClassName (ParentClassName) :
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
Example:-
class Father: Father
members of class Father Parent Class
• 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
Child Class
Syntax:-
class ParentClassName(object): object
members of Parent Class
Parent Class
class ChildClassName1(ParentClassName):
members of Child Class 2
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 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 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]
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
__init__.py
SMS
• 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
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
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
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.
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.
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.
• notify_all() – This method is used to wake up all threads waiting on the condition.
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
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
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.
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]()
Database Name
Row or Record or Tuple Entity Student
Table Name: Computer Science Column or Field or Attributes
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.
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))
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
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
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
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.