Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
SlideShare a Scribd company logo
4-Jan-20 1
Python - II
Copyright (c) SunilOS ( RAYS )
Technologies
www.raystec.com
www.sunilos.com
Application
One application is made of multiple modules
A Module is a file with extension .py
A module can define functions, classes and variables.
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 2
Module Module
Module Module
Application
Module
 Module is a file of .py extension
 Module may contain following
elements
o related functions
o related variables
o classes
 One .py file is a one Module
 Elements of one module can be
imported into another Module
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 3
variables
Functions
Module.py
class
UserService.py
 Following is UserService module which contains two methods add()
and update()
o def add( firstName, lastName ):
o print("Adding User")
o print('Name’,firstName, lastName)
o return
o def update( firstName, lastName ):
o print("Updating User")
o print('Name',firstName,lastName)
o return
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 4
TestUserService.py
 You can import a module by import statement in python
program. We are importing UserService.py module in
TestUserService.py file.
o import UserService
 Now you can use module functions:
o UserService.add("Ram" , "Sharma")
o UserService.update("Shyam" , "Sharma")
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 5
from … import statement
 You can import specific functions from a module using from … import
statement.
 TestUserModel.py may have following import statement
o from UserService import add,update
o add("Ram","Sharma")
o update("Shyam","Sharma")
 You can import all methods using * character
o from UserService import *
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 6
Module search path
 When you import a module, python interpreter searches module
in different directories in the following sequences:
o The current directory.
o If module is not found then searches each directory specified
in environment variable PYTHONPATH.
o If all fails then python checks the default path.
 You can set PYTHONPATH as per your app requirements
o set PYTHONPATH = c:pythonlib1;c:pythonlib2;
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 7
OOP
 Object Oriented Programming
 There are three key concepts of OOP
o Encapsulation: gather all related attributes and method.
o Inheritance: create expert classes
o Polymorphism: achieve dynamic behavior
 It achieves Modularity and Reusability
 One application is made of multiple objects at runtime
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 8
OOP Application Runtime
Application runtime is made of multiple objects
At runtime multiple objects collaborate to perform your
business operations
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 9
Application Runtime
Object Object Object
Object Object
Class; structure of an Object
Copyright (c) SunilOS ( RAYS ) Technologies 10
Realization
Realization
State/Variables
• currentGear
• Speed
• Color
Methods
• changeGear()
• accelerator()
• break()
• changeColor()
State/Variables
• name
• address
Methods
• changeName()
• changeAddress()
Structure
Real world entities based on
structure
4-Jan-20
Class
 Class is the data structure that defines structure of an object.
 Class contains related attributes and methods.
 Each class is an EXPERT class.
 Class is a Noun.
 Classes represent real world entities such as:
o Person
o Account
o Shape
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 11
Real World Entities – More Classes
Copyright (c) SunilOS ( RAYS ) Technologies 12
:Automobile
-color :String
-speed:int
-make:String
+$NO_OF_GEARS
+getColor():String
+setColor()
+getMake():String
+setMake()
+break()
+changeGear()
+accelerator()
+getSpeed():int
:Person
-name:String
-dob : Date
-address:String
+$AVG_AGE
+getName():String
+setName()
+getAdress():String
+setAddress()
+getDob (): Date
+setDob ()
+getAge() : int
:Account
-number:String
-accountType : String
-balance:double
+getNumber():String
+setNumber()
+getAccountType():String
+setAccountType()
+deposit ()
+withdrawal ()
+getBalance():double
+fundTransfer()
+payBill()
4-Jan-20
An Expert never overlap responsibilities
Copyright (c) SunilOS ( RAYS ) Technologies 13
Creator
Preserver
Destroyer
Trimurti
4-Jan-20
Object
 An object is the variable of type Class.
 You can create multiple objects of a Class.
 When memory is allocated to an object, object becomes instance.
 Memory allocation process of an object is called instantiation.
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 14
Class
Object
Object
Object
Experts bring Modularity and Reusability
Copyright (c) SunilOS ( RAYS ) Technologies 154-Jan-20
Create a Class
 A class is defined by ‘class’ keyword which is followed by
class name.
o class Person:
o ‘Contains person info‘
 First line in the class is a string which describes information of
the class.
 Class contains following members
o Class variables (attributes)
o Instance variables (attributes)
o Methods
o Constructor
o Destructor
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 16
Person Class
 class Person:
 count = 0 #class variable
 def __init__(self): #Constructor
 self.name = "" #instance variable
 Person.count += 1
 def setName(self,n): #Method
 self.name = n

 def getName(self): #Method
 return self.name
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 17
Test Person
 Lets create two objects p1 and p2 of class Person
o p1 = Person() #instantiation
o p1.setName("Ram")
o p2 = Person() #instantiation
o p2.setName("Shyam")
 Print value of objects
o print(p1.name)
o print(p1.getName())
o print(p2.getName())
o print(Person.count)
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 18
Class Vs Instance (Object) attributes
 Class attributes are defined and
initialized outside methods
o class Person:
 count = 0
 Memory is allocated to class
variables only once in its lifetime
 Class variable is accessed with
class name
o print(Person.count)
 Instance attributes are defined and
initialized inside constructer
o class Person:
 def
__init__(self):
• self.name =“”
 For each instance separate memory
is allocated to instance variables
 whereas instance variable is called
with object name
o p1 = Person()
o print(p1.name)
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 19
Constructor
 Each class has one constructor defined by __init__() method
 It is executed when object is instantiated
o p1 = Person()
 It is used to initialize instance variables
 def __init__(self):
• self.name = “Ram”
• self.address = “Mumbai”
 First parameter self is passed to access current instance of the class
 Optionally you can pass additional parameter to initialize class attributes:
 def __init__(self):
• self.name = “Ram”
• self.address = “Mumbai”
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 20
Methods
 Method is a function defined by def keyword
 Methods perform business operations and can change value of
member attributes
o class Person:
o def setName(self,n):
o self.name = n
o def getName(self):
o return self.name
 First parameter self is passed to each method to access
instance variables
o p1 = Person()
o p1.setName("Ram")
o print(p1.getName())
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 21
Class Methods
 A class method is called with class name
o Math.max(5,10)
 Class method does not require self as first parameter
o class Math:
o def max( a, b):
o if(a > b):
o return a
o else:
o return b
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 22
Object
 An object is the variable of type Class. You can create multiple objects of a
Class.
 When memory is allocated to an object, object is called instance and process
called instantiation.
 Here are person instances
o p1 = Person() #instantiation
o p1.setName("Ram")
o p2 = Person() #instantiation
o p2.setName("Shyam")
 You can print memory address of an object using id() method.
o print('ID', id(p1) )
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 23
Destructor __del__
 An object is garbage collected when it becomes orphan.
 Destructor method is called before an object is garbage collected
and removed from memory.
 Destructor is defined by __del__() method.
o def __del__(self):
o className = self.__class__.__name__
o print ("Destroying ", className )
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 24
Method __str__
 Method __str__ is used to define string representation of an object.
o def __str__( self ):
o return ”%s" % (self.name)
 When you print an object then string returned by this function is printed:
o print(p1)
 Remove an object from memory using del keyword:
o del p1
o del p2
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 25
Class metadata
 You can print class information using following attributes:
o print (“Person.__doc__:", Person.__doc__)
o print ("Person.__name__:", Person.__name__)
o print ("Person.__module__:", Person.__module__)
o print ("Person.__bases__:", Person.__bases__)
o print ("Person.__dict__:", Person.__dict__)
 Object dictionary
o print (p1.__dict__)
o print (p2.__dict__)
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 26
Encapsulation
 Gathering all related methods and attributes in a Class is called
encapsulation
 Here we have created Person class that has related attributes and
methods
 After encapsulation Expert classes are created
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 27
Inheritance
 Inheritance is a mechanism where a new class is derived from an
existing class.
 A class may inherit or reuse attributes and methods of other
class.
 A class derived from another class is called a subclass or child
class, whereas the class from which a subclass is derived is
called a superclass or parent class.
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 28
Super class
Child class Child class
Copyright (c) SunilOS ( RAYS ) Technologies 29
Inheritance
:Shape
color :String
borderWidth:int
getColor():String
setColor()
getBorderWidth():int
setBorderWidth()
:Rectangle
length :int
width:int
area()
getLength()
setLength()
:Circle
radius : int
area()
getRadius()
setRadius()
:Triangle
base:int
hight:int
area()
getBase()
setBase()
Circle c =new Circle();
c.getColor();
c.getBorderWidth();
c.area();
:object
UML
Notation
4-Jan-20
Why Inheritance ?
 When a class needs to define specialized behavior of a class then
inheritance is required
 For example Circle, Rectangle and Triangle are
providing specialized behavior of Shape class.
 Here Circle, Rectangle and Triangle are called
specialized classes whereas Shape is called generic class
 One class can inherit another class using following syntax:
o class Circle(Shape):
 By default object is root super class of all classes in python
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 30
Shape class
 class Shape:
o def __init__(self, c, b):
 self.color = c
 self.borderWidth = b
o def area(self):
 return -1
o def setColor(self, c):
 self.color = c
o def getColor(self):
 return self.color
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 31
:Shape
color :String
borderWidth:int
getColor():String
setColor()
getBorderWidth():int
setBorderWidth()
Circle class
 class Circle(Shape):
 PI = 3.14
 #c & b are optional
 def __init__(self, r, c=“”, b=0):
 self.radius = r
 super(Circle,self).__init__(c,b)
 def area(self): #override method
 return self.radius*self.radius*Circle.PI
 Create instance
o c1 = Circle(2,'Red',5)
o c2 = Circle(3,'Blue')
o c3 = Circle(4)
o print(c1.area())
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 32
Rectangle Class
 class Rectangle(Shape):
 def __init__(self, length, width , c='', b=0):
 self.length = length
 self.width = width
 super(Rectangle,self).__init__(c,b)

 def area(self):
 return self.length * self.length
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 33
Triangle Class
 class Triangle(Shape):
o def __init__(self, base, height , c='', b=0):
 self.base = base
 self.height = height
 super(Rectangle,self).__init__(c,b)
o def area(self):
 return (self.base * self.height) /2
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 34
Type of inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multi Inheritance
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 35
A
B
A
B
C
A
B C
A B
C
Multiple Inheritance
 Like C++, a class can be derived from more than one base
classes in Python. This is called multiple inheritance
 class Shape:
o ..
 class Design:
o ..
 class Circle(Shape, Design):
o ..
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 36
Method Overriding
 Child classes can override parent class methods
 Circle, Rectangle and Triangle child classes have
overridden area()method of Shape class
 class Shape:
o def area(self):
 return -1
 class Rectangle(Shape):
o def area(self):
 return self.length * self.length
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 37
Access Modifier
 Python has three types of access modifiers
o public, private, and protected.
 Public variables can be accessed inside or outside the class
 Private variables can only be accessed inside the class
 Protected variables can be accessed within the same package
 Variable name is prefixed by double underscore (__) to make it private
 Variable name is prefixed by single underscore (_) to make it protected
 Public variables do not have any prefixes
 class Employee:
o def __init__(self):
 self.name = “Ram" #public
 self._code = “E101” #protected
 self.__salary= 25000 #private
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 38
Abstract Classes
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 39
Abstract class
 Abstract classes are classes that contain one or more abstract
methods
 An abstract method is a method that is declared, but contains no
implementation
 Abstract classes may not be instantiated
 Subclasses are required to provide implementations for the
abstract methods
 For example area() method in Shape class does not have
implementation. Area implementation must be provided by child
classes Circle, Rectangle and Triangle
 Shape will be an abstract class because area()is an abstract
method
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 40
Create an abstract class
 Python provides a module to define Abstract Base Classes (ABCs).
 This module is called abc
 You can import abc module using following command:
o from abc import ABC, abstractmethod
 Abstract class is inherited from ABC class and abstract method is annotated by
@abstractmethod annotation
o class Shape(ABC):
o def __init__(self, c, b):
o self.color = c
o self.borderWidth = b
o @abstractmethod
o def area(self):
o pass
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 41
Child class
 Child class must implement abstract methods otherwise child will become abstract
 from abc import ABC, abstractmethod
 class Shape(ABC):
 @abstractmethod
 def area(self):
 pass
 class Circle(Shape):
 PI = 3.14
 def area(self):
 return self.radius * self.radius * Circle.PI
 c = Circle(10,"Red",2)
 print(c.area())
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 42
Exception Handling
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 43
throw
catch
• Exception causes abnormal termination of
program or wrong execution result.
• Python provides an exception handling
mechanism to handle exceptions.
• Exception handling is done by try-except-
else-finally blocks.
• Exception raised in try block is caught by
except block.
• Block finally is optional and always
executed.
Exception Handling
Exception is an error in a program execution that
breaks the normal flow of program.
When you handle these exceptions and execute an
alternate path of program then it is called exception
handling.
Exceptions are handled by following blocks
o try/except
o try/finally
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 44
try-except
 a =4
 b = 0
 try:
 c= a/b
 print('C:',c)
 except ZeroDivisionError:
 print("check your dividend is Zero")
 Block except can handle multiple exceptions.
o except ex1,ex2,ex3
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 45
Print exception message
 try:
 c= a/b
 print('C:',c)
 except ZeroDivisionError as e:
 print(“Exception:", e)
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 46
try-except-else
 a =4
 b = 2
 try:
 c= a/b
 print('C:',c)
 except ZeroDivisionError:
 print("check your division is Zero")
 else: # it will be executed when no exception
 print("Your division was greater than zero")
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 47
try-finally
 try:
 c= a/b
 print('C:',c)
 except ZeroDivisionError as e:
 print("Check your division is Zero", e)
 finally:
 print(“Always executed")
 Finally block will be executed whether exception is occurred or
not.
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 48
Raise an Exception
 You can raise your custom exception using raise statement
 Raise statement throws instance of Exception class
 try:
 number = int(input("Enter your Number :"))
 if number > 10:
 raise Exception(‘invalid number')
 except Exception as e:
 print(e)
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 49
Custom Exception
TODO
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 50
Exception List
8
EOFError: Raised when there is no input from either the raw_input() or input()
function and the end of file is reached.
9 ImportError: Raised when an import statement fails.
10 IndexError: Raised when an index is not found in a sequence.
11 KeyError: Raised when the specified key is not found in the dictionary.
12 NameError: Raised when an identifier is not found in the local or global namespace.
13
IOError: Raised when an input/ output operation fails, such as the print statement or
the open() function when trying to open a file that does not exist.
14 RuntimeError: Raised when a generated error does not fall into any category.
15
NotImplementedError: Raised when an abstract method that needs to be implemented
in an inherited class is not actually implemented.
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 51
Exception List
# Exception Name & Description
1 Exception :Base class for all exceptions
2
StopIteration :Raised when the next() method of an iterator does not point to
any object.
3 ArithmeticError: Base class for all errors that occur for numeric calculation.
4
OverflowError: Raised when a calculation exceeds maximum limit for a
numeric type.
5 FloatingPointError: Raised when a floating point calculation fails.
6
ZeroDivisionError: Raised when division or modulo by zero takes place for all
numeric types.
7 AttributeError:Raised in case of failure of attribute reference or assignment.
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 52
File IO
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 53
File IO
 Python provides basic functions to read and write a text and
binary files.
 Function open() is used to open a file into read or write mode.
o file = open(“Hello.txt")
 File can be opened in different mode like read, write, append etc.
o file = open(“Hello.txt“,”w”)
 A file can be closed by its close() method
o file.close()
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 54
File Info
 Here is program to read file information
o fo = open("Test.py", “rw”, 0)
o print ("File Name: ", fo.name)
o print ("Mode of Opening: ", fo.mode)
o print ("Is Closed: ", fo.closed)
o fo.close()
 Parameters of open function are:
o Name
o Mode
o Buffering 0: No 1: Yes
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 55
Read from File
Here is program that read entire text from file:
o file = open(“Hello.txt") //open a file
o text = file.read() # read all text
o print(text)
o file.close() # close the file
o return
Read binary data
o bArray = file.read(10);
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 56
Read Line by Line
You can read file line by line using for loop
o file = open(“Hello.txt")
o for line in file:
o print(line)
o file.close()
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 57
Write to a File
Write into a file using write mode
o file = open("Test.txt","w")
o file.write("Hin")
o file.write("This is Python file")
o file.close()
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 58
With Statement
 It is used to manage the resources
 It makes code more cleaner
 It automatically closes file when block is finish
 with open("Test.txt","w")as file:
o file.write("Hin")
o file.write("This is Python file")
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 59
File Position
 str = fo.read(10);
 position = fo.tell();
 position = fo.seek(0, 0)
 import os
 os.rename( "test1.txt", "test2.txt" )
 os.remove("text2.txt")
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 60
Mode of File
Mode Description
r Opens a file for reading only. (It's a default mode.)
w
Opens a file for writing. (If a file doesn't exist already, then it creates a
new file, otherwise, it's truncate a file.)
x
Opens a file for exclusive creation. (Operation fails if a file does not exist
in the location.)
a
Opens a file for appending at the end of the file without truncating it.
(Creates a new file if it does not exist in the location.)
t Opens a file in text mode. (It's a default mode.)
b Opens a file in binary mode.
+ Opens a file for updating (reading and writing.)
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 61
Object Serialization
 You may need to store an object into a file or send over the
network that time you need to convert your object into byte
stream, this is called serialization.
 When you restore object from byte stream then it is called
deserialization
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 62
Serialization Deserialization
https://pmm.nasa.gov/education/water-cycle
Object Serialization
 The pickle module is used to serialize and de-serialize an object
 Serializing process is called Pickling
 De-serializing process is called Unpickling
 Here we are storing employee object into emp.dat file
 import pickle
 class Employee:
 def __init__(self,eno,ename):
 self.eno=eno
 self.ename=ename
 e = Employee(1,'Mayank')
 f = open('emp.dat','wb')
 pickle.dump(e,f)
 f.close()
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 63
Unpickling
import pickle
f = open('emp.dat','wb’)
e = pickle.load(f)
f.close()
print(e.name)
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 64
Concurrency and Theading
4-Jan-20
Copyright (c) SunilOS ( RAYS )
Technologies 65
Copyright (c) SunilOS ( RAYS ) Technologies 66
Process
 A process has a self-contained execution environment.
 A process generally has a complete, private set of basic run-time
resources; in particular, each process has its own memory space.
 Python program is executed as a single process.
4-Jan-20
Copyright (c) SunilOS ( RAYS ) Technologies 67
Concurrency vs. Parallelism
CPU CPU1 CPU2
4-Jan-20
Copyright (c) SunilOS ( RAYS ) Technologies 68
Thread
 Threads are sometimes called lightweight processes.
 Both processes and threads provide an execution environment,
but creating a new thread requires fewer resources than creating
a new process.
 Threads exist within a process
 Every process (application) has at least one thread.
 Threads share resources of their process. Resource are memory
and open files.
 Each thread is associated with an instance of the class Thread
4-Jan-20
Copyright (c) SunilOS ( RAYS ) Technologies 69
Threads and Processes
4-Jan-20
Copyright (c) SunilOS ( RAYS ) Technologies 70
Multitasking & Multithreading
 Multitasking refers to a computer's ability to perform multiple
jobs concurrently. Multitasking means more than one programs
are running together on a single machine.
 A thread is a single sequence of execution within a program.
 Multithreading refers to multiple threads of control within a
single program. Each program can run multiple threads of
control within it, e.g., Web Browser.
4-Jan-20
HelloWithoutThread
 Let’s create two functions hello() and hi(). Run both functions without
thread
 def hello():
 for i in range(15):
 print ( 'Hello ',i)
 def hi():
 for i in range(15):
 print ( 'Hi ‘,i)
 hello()
 hi()
 Both functions will be executed sequentially
Copyright (c) SunilOS ( RAYS ) Technologies 714-Jan-20
HelloWithoutThread output
 Hello 0
 Hello 1
 Hello 2
 …
 Hello 14
 Hi 0
 Hi 1
 Hi 2
 ..
 Hi 14
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 72
Hello With Thread
 Let’s create two threads and run hello() and hi()functions inside
thread.
 import threading
 from threading import *
 ..
 t1 = threading.Thread(target = hello)
 t2 = threading.Thread(target = hi)
 #Start threads
 t1.start()
 t2.start()
 Both functions will be executed concurrently
Copyright (c) SunilOS ( RAYS ) Technologies 734-Jan-20
Hello With Thread output
 Hello 0
 Hello 1
 Hello 2
 Hi 0
 Hello 3
 …
 Hi 10
 Hello 14
 Hi 11
 Hi 13
 Hi 14
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 74
Copyright (c) SunilOS ( RAYS ) Technologies 75
Thread
4-Jan-20
Raktabija
1. Raktabija had a capability to
create another Raktbija by
his single drop of blood.
2. Created Raktabija will be
equally powerful, and can
consume same kind of
resources and work
concurrently.
3. If one Raktabija dies another
will remain active and live.
1. Likewise a Thread can create
another thread.
2. Created Thread will be
equally powerful, and can
consume same kind of
resources and work
concurrently.
3. If one thread dies, other will
remain active in memory.
Copyright (c) SunilOS ( RAYS ) Technologies 76
http://en.wikipedia.org/wiki/Raktavija
4-Jan-20
Copyright (c) SunilOS ( RAYS ) Technologies 77
Creating Threads
 There are two ways to create a Thread
o Create a function and use Thread object to run this function
inside thread
o Inherit Thread class and override run() method
 You need to import threading module to make a thread
o import threading
o from threading import *
4-Jan-20
Function as thread
 Create a function and pass its name to target attribute of Thread
constructor
 import threading
 from threading import *
 def hello():
 for i in range(15):
 print ( 'Hello’, i )
 #create thread
 t1 = threading.Thread(target = hello)
 #Start threads
 t1.start()
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 78
Parametrized function as thread
 Pass argument array to args attribute of Thread constructor
 def hello(name):
 for i in range(15):
 print ( name , i)
 t3 = threading.Thread(target=hello, args=('Ram',))
 t4 = threading.Thread(target=hello, args=('Shyam',))
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 79
Inherit Thread class
 Inherit Thread class and override run() method
 class Hi(Thread):
 def run(self):
 for i in range(15):
 print("Hi", i )
 #Create thread
 t1= Hi()
 #Start thread
 t1.start()
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 80
Daemon Threads
 Daemon threads are “background” threads, that provide services
to other threads, e.g., the garbage collection thread
 Program will not exit if non-Daemon threads are executing
 Program will exit if only Daemon threads are executing
 You can make a daemon thread by
 t1 = threading.Thread(target=hello, daemon=True)
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 81
Thread Constructor
 class threading.Thread (group=None, target=None,
name=None, args=(), kwargs={}, *, daemon=None)
 group should be None; reserved for future use
 target is the callable function
 args is the argument tuple for the target function
 name of the thread
 kwargs is a dictionary of keyword arguments for the target invocation.
Defaults to {}.
 daemon if given True, it makes thread daemon
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 82
Thread handling
 threading.active_count() : returns count of active alive threads
 threading.current_thread(): returns current thread object
 threading.get_ident(): returns id of the current thread
 threading.enumerate(): return a list of all Thread objects
currently alive
 threading.main_thread(): return of main thread that started
Python interpreter
 threading.TIMEOUT_MAX: The maximum value allowed for
the timeout to a blocking function
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 83
Synchronization
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 84
Synchronization
 Synchronisation is applied on objects or functions, those are
shared by concurrent threads
 Syncronization make sure that a shared resource can be accessed
by only one thread at a time
 Syncronized resources are accessed sequencially by concurrent
threads
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 85
Race condition
Syncronization causes race condition among Threads
Threading module provides a Lock class to deal with
the race condition
Following are methods of Lock class:
o lock = threading.Lock(): It creates a lock object
o lock.acquire(): It acquires the lock for current thread
o lock.release(): It releases the lock
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 86
Account Class
 Lets create an Account class which will be accessed by concurrent threads
o class Account:
o balance =0
o def get_balance(self):
o sleep(2)
o return self.balance
o def set_balance(self, amount):
o sleep(2)
o self.balance = amount
o def diposite(self, amount):
o bal = self.get_balance()
o self.set_balance(bal + amount)
 It is assumed that set and get balance operation takes 2 seconds to execute
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 87
Racing Thread
 class Racing(Thread):
 account: Account
 name = ""
 def __init__(self,account, name):
 super().__init__()
 self.account = account
 self.name = name
 def run(self):
 for i in range(5):
 self.account.diposite(100)
 print( self.name, self.account.get_balance())
 t1 = Racing(acc, "Ram")
 t2 = Racing(acc, "Shyam")
 t1.start()
 t2.start()
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 88
• Racing thread is depositing
Rs 1000 five times in the
account
• Two threads are started and
both are racing to deposit
amount
Output
 Shyam 100
 Ram 100
 Shyam 200
 Ram 200
 Ram 300
 Shyam 300
 Ram 400
 Shyam 400
 Shyam 500
 Ram 500
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 89
Synchronize deposit
 class Account:
 balance =0
 def __init__(self):
 self.lock = threading.Lock()
 def get_balance(self):
 sleep(2)
 return self.balance
 def set_balance(self, amount):
 sleep(2)
 self.balance = amount

 def diposite(self, amount):
 self.lock.acquire()
 bal = self.get_balance()
 self.set_balance(bal + amount)
 self.lock.release()
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 90
Output
 Ram 100
 Shyam 200
 Ram 300
 Shyam 400
 Ram 500
 Shyam 600
 Ram 700
 Shyam 800
 Ram 900
 Shyam 1000
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 91
 Emails are sent by SMTP protocol
 Module smtplib is used to send an email
 You can send plain text or HTML text in email body
 You can attach files with emails
 Following SMTP servers can be used to send an email
o GMail
o Yahoo
o Hotmail
o Etc.
Email
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 92
Send Plain Text in Email
 import smtplib
 smtp_server = "smtp.gmail.com"
 port = 587 # For TLS
 sender_email = "webmaster@sunrays.co.in"
 password = input("Enter password and press enter: ")
 receiver_email = “myfriend@gmail.com"
 message = """From: Sunil Sahu <webmaster@nenosystems.com>
 CC: sunil.sahu@nenosystems.com
 Subject : Hi from python

<H1>HI this is my first email from Python.</H1>
 """
 smtp = smtplib.SMTP(smtp_server,port)
 smtp.starttls() #Enable transport layer security
 smtp.login(sender_email,password)
 smtp.sendmail(sender_email, receiver_email, message)
 smtp.quit()
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 93
Secure Email
 An SMTP connection is secured and encrypted so that message and login credentials
are not easily accessed by others
 SSL (Secure Sockets Layer) and TLS (Transport Layer Security) are two protocols
that can be used to encrypt an SMTP connection.
 Gmail SMTP server provides 465 port for SSL and 587 port for TLS connection
 There are two ways to secure connection
 Making SSL connection
 connection = smtplib.SMTP_SSL(smtp_server, 465)
 connection.login(sender_email,password)
 Enable TLS by calling method smtplib.starttls()
 connection = smtplib.SMTP(smtp_server, 587)
 connection.starttls()
 connection.login(sender_email,password)
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 94
Email Subject & Body
 Email contains subject and body text message
 Subject and body text are delimited by two new line characters
(nn) and prefixed by “Subject : ” word
o subject = "First Email"
o text = "How are you ?"
o body = "Subject: " + subject + " nn " + text
o connection.sendmail(sender_email, receiver_email, body)
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 95
HTML content
 Python provides MIME (Multipurpose Internet Mail Extensions) Multipart
emails.
 Mutiple part email contains mutiple parts in email like plain text, html text,
files etc.
 It is used to send HTML emails and file attachements
 Module email.mime provides classes to make mutiple part emails.
o import smtplib
o from email.mime.multipart import MIMEMultipart
o from email.mime.text import MIMEText
o from email.mime.base import MIMEBase
o from email import encoders
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 96
Send HTML Email
 text = “Hi How are you”
 html = "<html><body><h1>Hi, How are you</h1></body></html>

 msg = MIMEMultipart() # instance of MIMEMultipart
 msg['From'] = sender_email # storing the senders email address
 msg['To'] = receiver_email # storing the receivers email address
 msg['Subject'] = "This is Mutipart email" # storing the subject
 msg.attach(MIMEText(text, 'plain')) #plain text part
 msg.attach(MIMEText(html, 'html')) #html text part

 s = smtplib.SMTP('smtp.gmail.com', 587)
 s.starttls()
 s.login(sender_email, password)
 s.sendmail(sender_email, receiver_email, msg.as_string())
 s.quit()
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 97
Attach A File
 In multipart email you can also attach one or more files as a part.
 filename = "SimpleMail.py"
 with open(filename, "rb") as attachment:
 # instance of MIME Base and named as p
 p = MIMEBase('application', 'octet-stream')
 # To change the payload into encoded form
 p.set_payload((attachment).read())
 # encode into base64
 encoders.encode_base64(p)
 p.add_header('Content-Disposition’ , "attachment;
filename= %s" % filename)
 # attach the instance 'p' to instance 'msg'
 msg.attach(p)
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 98
Tkinter
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 99
Networking
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 100
Database Connectivity
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 101
DJango
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 102
References
 https://docs.python.org/3/library/threading.html
 https://realpython.com/python-send-email/
 https://likegeeks.com/python-gui-examples-tkinter-tutorial/
4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 103

More Related Content

What's hot

Exception Handling
Exception HandlingException Handling
Exception Handling
Sunil OS
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
Sunil OS
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
Sunil OS
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
Sunil OS
 
JDBC
JDBCJDBC
JDBC
Sunil OS
 
Threads V4
Threads  V4Threads  V4
Threads V4
Sunil OS
 
OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
Sunil OS
 
C Basics
C BasicsC Basics
C Basics
Sunil OS
 
Log4 J
Log4 JLog4 J
Log4 J
Sunil OS
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS
 
Hibernate
Hibernate Hibernate
Hibernate
Sunil OS
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
Sunil OS
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
Sunil OS
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
Sunil OS
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
Sunil OS
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
Sunil OS
 
Java Basics
Java BasicsJava Basics
Java Basics
Sunil OS
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
Sunil OS
 
CSS
CSS CSS
CSS
Sunil OS
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
Sunil OS
 

What's hot (20)

Exception Handling
Exception HandlingException Handling
Exception Handling
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
Java 8 - CJ
Java 8 - CJJava 8 - CJ
Java 8 - CJ
 
JDBC
JDBCJDBC
JDBC
 
Threads V4
Threads  V4Threads  V4
Threads V4
 
OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
 
C Basics
C BasicsC Basics
C Basics
 
Log4 J
Log4 JLog4 J
Log4 J
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Hibernate
Hibernate Hibernate
Hibernate
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
 
Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Java Basics
Java BasicsJava Basics
Java Basics
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
CSS
CSS CSS
CSS
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 

Similar to Python part2 v1

03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
SyedUmairAli9
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
NuurAxmed2
 
Objective c
Objective cObjective c
Objective c
ricky_chatur2005
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
arjun431527
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
Sasidhar Kothuru
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
Sasidhar Kothuru
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
KALAISELVI P
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
Muhammed Thanveer M
 
Python classes objects
Python classes objectsPython classes objects
My c++
My c++My c++
My c++
snathick
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Php oop (1)
Php oop (1)Php oop (1)
Php oop (1)
Sudip Simkhada
 
PythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programmingPythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programming
KhadijaKhadijaAouadi
 
C++ oop
C++ oopC++ oop
C++ oop
Sunil OS
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
Ahmed Swilam
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 

Similar to Python part2 v1 (20)

03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
Objective c
Objective cObjective c
Objective c
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Spsl vi unit final
Spsl vi unit finalSpsl vi unit final
Spsl vi unit final
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
My c++
My c++My c++
My c++
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
Php oop (1)
Php oop (1)Php oop (1)
Php oop (1)
 
PythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programmingPythonOO.pdf oo Object Oriented programming
PythonOO.pdf oo Object Oriented programming
 
C++ oop
C++ oopC++ oop
C++ oop
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 

More from Sunil OS

OOP v3
OOP v3OOP v3
OOP v3
Sunil OS
 
Threads v3
Threads v3Threads v3
Threads v3
Sunil OS
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
Sunil OS
 
Python Pandas
Python PandasPython Pandas
Python Pandas
Sunil OS
 
Angular 8
Angular 8 Angular 8
Angular 8
Sunil OS
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
Sunil OS
 
C# Basics
C# BasicsC# Basics
C# Basics
Sunil OS
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
Sunil OS
 
C++
C++C++
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
Sunil OS
 

More from Sunil OS (10)

OOP v3
OOP v3OOP v3
OOP v3
 
Threads v3
Threads v3Threads v3
Threads v3
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Angular 8
Angular 8 Angular 8
Angular 8
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
 
C++
C++C++
C++
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 

Recently uploaded

Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptxChapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Brajeswar Paul
 
Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and RemediesArdra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Astro Pathshala
 
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISINGSYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
Dr Vijay Vishwakarma
 
Understanding and Interpreting Teachers’ TPACK for Teaching Multimodalities i...
Understanding and Interpreting Teachers’ TPACK for Teaching Multimodalities i...Understanding and Interpreting Teachers’ TPACK for Teaching Multimodalities i...
Understanding and Interpreting Teachers’ TPACK for Teaching Multimodalities i...
Neny Isharyanti
 
Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024
Elizabeth Walsh
 
The basics of sentences session 9pptx.pptx
The basics of sentences session 9pptx.pptxThe basics of sentences session 9pptx.pptx
The basics of sentences session 9pptx.pptx
heathfieldcps1
 
Righteous among Nations - eTwinning e-book (1).pdf
Righteous among Nations - eTwinning e-book (1).pdfRighteous among Nations - eTwinning e-book (1).pdf
Righteous among Nations - eTwinning e-book (1).pdf
Zuzana Mészárosová
 
(T.L.E.) Agriculture: Essentials of Gardening
(T.L.E.) Agriculture: Essentials of Gardening(T.L.E.) Agriculture: Essentials of Gardening
(T.L.E.) Agriculture: Essentials of Gardening
MJDuyan
 
No, it's not a robot: prompt writing for investigative journalism
No, it's not a robot: prompt writing for investigative journalismNo, it's not a robot: prompt writing for investigative journalism
No, it's not a robot: prompt writing for investigative journalism
Paul Bradshaw
 
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ..."DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
thanhluan21
 
Views in Odoo - Advanced Views - Pivot View in Odoo 17
Views in Odoo - Advanced Views - Pivot View in Odoo 17Views in Odoo - Advanced Views - Pivot View in Odoo 17
Views in Odoo - Advanced Views - Pivot View in Odoo 17
Celine George
 
Bedok NEWater Photostory - COM322 Assessment (Story 2)
Bedok NEWater Photostory - COM322 Assessment (Story 2)Bedok NEWater Photostory - COM322 Assessment (Story 2)
Bedok NEWater Photostory - COM322 Assessment (Story 2)
Liyana Rozaini
 
Credit limit improvement system in odoo 17
Credit limit improvement system in odoo 17Credit limit improvement system in odoo 17
Credit limit improvement system in odoo 17
Celine George
 
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUMENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
HappieMontevirgenCas
 
L1 L2- NLC PPT for Grade 10 intervention
L1 L2- NLC PPT for Grade 10 interventionL1 L2- NLC PPT for Grade 10 intervention
L1 L2- NLC PPT for Grade 10 intervention
RHODAJANEAURESTILA
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
heathfieldcps1
 
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY pdf- [Autosaved].pdf
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY  pdf-  [Autosaved].pdfARCHITECTURAL PATTERNS IN HISTOPATHOLOGY  pdf-  [Autosaved].pdf
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY pdf- [Autosaved].pdf
DharmarajPawar
 
NationalLearningCamp-2024-Orientation-for-RO-SDO.pptx
NationalLearningCamp-2024-Orientation-for-RO-SDO.pptxNationalLearningCamp-2024-Orientation-for-RO-SDO.pptx
NationalLearningCamp-2024-Orientation-for-RO-SDO.pptx
CelestineMiranda
 
How to Show Sample Data in Tree and Kanban View in Odoo 17
How to Show Sample Data in Tree and Kanban View in Odoo 17How to Show Sample Data in Tree and Kanban View in Odoo 17
How to Show Sample Data in Tree and Kanban View in Odoo 17
Celine George
 
BRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptx
BRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptxBRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptx
BRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptx
kambal1234567890
 

Recently uploaded (20)

Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptxChapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
Chapter-2-Era-of-One-party-Dominance-Class-12-Political-Science-Notes-2 (1).pptx
 
Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and RemediesArdra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
Ardra Nakshatra (आर्द्रा): Understanding its Effects and Remedies
 
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISINGSYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
SYBCOM SEM III UNIT 1 INTRODUCTION TO ADVERTISING
 
Understanding and Interpreting Teachers’ TPACK for Teaching Multimodalities i...
Understanding and Interpreting Teachers’ TPACK for Teaching Multimodalities i...Understanding and Interpreting Teachers’ TPACK for Teaching Multimodalities i...
Understanding and Interpreting Teachers’ TPACK for Teaching Multimodalities i...
 
Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024Howe Writing Center - Orientation Summer 2024
Howe Writing Center - Orientation Summer 2024
 
The basics of sentences session 9pptx.pptx
The basics of sentences session 9pptx.pptxThe basics of sentences session 9pptx.pptx
The basics of sentences session 9pptx.pptx
 
Righteous among Nations - eTwinning e-book (1).pdf
Righteous among Nations - eTwinning e-book (1).pdfRighteous among Nations - eTwinning e-book (1).pdf
Righteous among Nations - eTwinning e-book (1).pdf
 
(T.L.E.) Agriculture: Essentials of Gardening
(T.L.E.) Agriculture: Essentials of Gardening(T.L.E.) Agriculture: Essentials of Gardening
(T.L.E.) Agriculture: Essentials of Gardening
 
No, it's not a robot: prompt writing for investigative journalism
No, it's not a robot: prompt writing for investigative journalismNo, it's not a robot: prompt writing for investigative journalism
No, it's not a robot: prompt writing for investigative journalism
 
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ..."DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
"DANH SÁCH THÍ SINH XÉT TUYỂN SỚM ĐỦ ĐIỀU KIỆN TRÚNG TUYỂN ĐẠI HỌC CHÍNH QUY ...
 
Views in Odoo - Advanced Views - Pivot View in Odoo 17
Views in Odoo - Advanced Views - Pivot View in Odoo 17Views in Odoo - Advanced Views - Pivot View in Odoo 17
Views in Odoo - Advanced Views - Pivot View in Odoo 17
 
Bedok NEWater Photostory - COM322 Assessment (Story 2)
Bedok NEWater Photostory - COM322 Assessment (Story 2)Bedok NEWater Photostory - COM322 Assessment (Story 2)
Bedok NEWater Photostory - COM322 Assessment (Story 2)
 
Credit limit improvement system in odoo 17
Credit limit improvement system in odoo 17Credit limit improvement system in odoo 17
Credit limit improvement system in odoo 17
 
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUMENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
ENGLISH-7-CURRICULUM MAP- MATATAG CURRICULUM
 
L1 L2- NLC PPT for Grade 10 intervention
L1 L2- NLC PPT for Grade 10 interventionL1 L2- NLC PPT for Grade 10 intervention
L1 L2- NLC PPT for Grade 10 intervention
 
The basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptxThe basics of sentences session 10pptx.pptx
The basics of sentences session 10pptx.pptx
 
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY pdf- [Autosaved].pdf
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY  pdf-  [Autosaved].pdfARCHITECTURAL PATTERNS IN HISTOPATHOLOGY  pdf-  [Autosaved].pdf
ARCHITECTURAL PATTERNS IN HISTOPATHOLOGY pdf- [Autosaved].pdf
 
NationalLearningCamp-2024-Orientation-for-RO-SDO.pptx
NationalLearningCamp-2024-Orientation-for-RO-SDO.pptxNationalLearningCamp-2024-Orientation-for-RO-SDO.pptx
NationalLearningCamp-2024-Orientation-for-RO-SDO.pptx
 
How to Show Sample Data in Tree and Kanban View in Odoo 17
How to Show Sample Data in Tree and Kanban View in Odoo 17How to Show Sample Data in Tree and Kanban View in Odoo 17
How to Show Sample Data in Tree and Kanban View in Odoo 17
 
BRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptx
BRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptxBRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptx
BRIGADA ESKWELA OPENING PROGRAM KICK OFF.pptx
 

Python part2 v1

  • 1. 4-Jan-20 1 Python - II Copyright (c) SunilOS ( RAYS ) Technologies www.raystec.com www.sunilos.com
  • 2. Application One application is made of multiple modules A Module is a file with extension .py A module can define functions, classes and variables. 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 2 Module Module Module Module Application
  • 3. Module  Module is a file of .py extension  Module may contain following elements o related functions o related variables o classes  One .py file is a one Module  Elements of one module can be imported into another Module 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 3 variables Functions Module.py class
  • 4. UserService.py  Following is UserService module which contains two methods add() and update() o def add( firstName, lastName ): o print("Adding User") o print('Name’,firstName, lastName) o return o def update( firstName, lastName ): o print("Updating User") o print('Name',firstName,lastName) o return 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 4
  • 5. TestUserService.py  You can import a module by import statement in python program. We are importing UserService.py module in TestUserService.py file. o import UserService  Now you can use module functions: o UserService.add("Ram" , "Sharma") o UserService.update("Shyam" , "Sharma") 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 5
  • 6. from … import statement  You can import specific functions from a module using from … import statement.  TestUserModel.py may have following import statement o from UserService import add,update o add("Ram","Sharma") o update("Shyam","Sharma")  You can import all methods using * character o from UserService import * 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 6
  • 7. Module search path  When you import a module, python interpreter searches module in different directories in the following sequences: o The current directory. o If module is not found then searches each directory specified in environment variable PYTHONPATH. o If all fails then python checks the default path.  You can set PYTHONPATH as per your app requirements o set PYTHONPATH = c:pythonlib1;c:pythonlib2; 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 7
  • 8. OOP  Object Oriented Programming  There are three key concepts of OOP o Encapsulation: gather all related attributes and method. o Inheritance: create expert classes o Polymorphism: achieve dynamic behavior  It achieves Modularity and Reusability  One application is made of multiple objects at runtime 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 8
  • 9. OOP Application Runtime Application runtime is made of multiple objects At runtime multiple objects collaborate to perform your business operations 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 9 Application Runtime Object Object Object Object Object
  • 10. Class; structure of an Object Copyright (c) SunilOS ( RAYS ) Technologies 10 Realization Realization State/Variables • currentGear • Speed • Color Methods • changeGear() • accelerator() • break() • changeColor() State/Variables • name • address Methods • changeName() • changeAddress() Structure Real world entities based on structure 4-Jan-20
  • 11. Class  Class is the data structure that defines structure of an object.  Class contains related attributes and methods.  Each class is an EXPERT class.  Class is a Noun.  Classes represent real world entities such as: o Person o Account o Shape 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 11
  • 12. Real World Entities – More Classes Copyright (c) SunilOS ( RAYS ) Technologies 12 :Automobile -color :String -speed:int -make:String +$NO_OF_GEARS +getColor():String +setColor() +getMake():String +setMake() +break() +changeGear() +accelerator() +getSpeed():int :Person -name:String -dob : Date -address:String +$AVG_AGE +getName():String +setName() +getAdress():String +setAddress() +getDob (): Date +setDob () +getAge() : int :Account -number:String -accountType : String -balance:double +getNumber():String +setNumber() +getAccountType():String +setAccountType() +deposit () +withdrawal () +getBalance():double +fundTransfer() +payBill() 4-Jan-20
  • 13. An Expert never overlap responsibilities Copyright (c) SunilOS ( RAYS ) Technologies 13 Creator Preserver Destroyer Trimurti 4-Jan-20
  • 14. Object  An object is the variable of type Class.  You can create multiple objects of a Class.  When memory is allocated to an object, object becomes instance.  Memory allocation process of an object is called instantiation. 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 14 Class Object Object Object
  • 15. Experts bring Modularity and Reusability Copyright (c) SunilOS ( RAYS ) Technologies 154-Jan-20
  • 16. Create a Class  A class is defined by ‘class’ keyword which is followed by class name. o class Person: o ‘Contains person info‘  First line in the class is a string which describes information of the class.  Class contains following members o Class variables (attributes) o Instance variables (attributes) o Methods o Constructor o Destructor 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 16
  • 17. Person Class  class Person:  count = 0 #class variable  def __init__(self): #Constructor  self.name = "" #instance variable  Person.count += 1  def setName(self,n): #Method  self.name = n   def getName(self): #Method  return self.name 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 17
  • 18. Test Person  Lets create two objects p1 and p2 of class Person o p1 = Person() #instantiation o p1.setName("Ram") o p2 = Person() #instantiation o p2.setName("Shyam")  Print value of objects o print(p1.name) o print(p1.getName()) o print(p2.getName()) o print(Person.count) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 18
  • 19. Class Vs Instance (Object) attributes  Class attributes are defined and initialized outside methods o class Person:  count = 0  Memory is allocated to class variables only once in its lifetime  Class variable is accessed with class name o print(Person.count)  Instance attributes are defined and initialized inside constructer o class Person:  def __init__(self): • self.name =“”  For each instance separate memory is allocated to instance variables  whereas instance variable is called with object name o p1 = Person() o print(p1.name) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 19
  • 20. Constructor  Each class has one constructor defined by __init__() method  It is executed when object is instantiated o p1 = Person()  It is used to initialize instance variables  def __init__(self): • self.name = “Ram” • self.address = “Mumbai”  First parameter self is passed to access current instance of the class  Optionally you can pass additional parameter to initialize class attributes:  def __init__(self): • self.name = “Ram” • self.address = “Mumbai” 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 20
  • 21. Methods  Method is a function defined by def keyword  Methods perform business operations and can change value of member attributes o class Person: o def setName(self,n): o self.name = n o def getName(self): o return self.name  First parameter self is passed to each method to access instance variables o p1 = Person() o p1.setName("Ram") o print(p1.getName()) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 21
  • 22. Class Methods  A class method is called with class name o Math.max(5,10)  Class method does not require self as first parameter o class Math: o def max( a, b): o if(a > b): o return a o else: o return b 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 22
  • 23. Object  An object is the variable of type Class. You can create multiple objects of a Class.  When memory is allocated to an object, object is called instance and process called instantiation.  Here are person instances o p1 = Person() #instantiation o p1.setName("Ram") o p2 = Person() #instantiation o p2.setName("Shyam")  You can print memory address of an object using id() method. o print('ID', id(p1) ) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 23
  • 24. Destructor __del__  An object is garbage collected when it becomes orphan.  Destructor method is called before an object is garbage collected and removed from memory.  Destructor is defined by __del__() method. o def __del__(self): o className = self.__class__.__name__ o print ("Destroying ", className ) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 24
  • 25. Method __str__  Method __str__ is used to define string representation of an object. o def __str__( self ): o return ”%s" % (self.name)  When you print an object then string returned by this function is printed: o print(p1)  Remove an object from memory using del keyword: o del p1 o del p2 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 25
  • 26. Class metadata  You can print class information using following attributes: o print (“Person.__doc__:", Person.__doc__) o print ("Person.__name__:", Person.__name__) o print ("Person.__module__:", Person.__module__) o print ("Person.__bases__:", Person.__bases__) o print ("Person.__dict__:", Person.__dict__)  Object dictionary o print (p1.__dict__) o print (p2.__dict__) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 26
  • 27. Encapsulation  Gathering all related methods and attributes in a Class is called encapsulation  Here we have created Person class that has related attributes and methods  After encapsulation Expert classes are created 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 27
  • 28. Inheritance  Inheritance is a mechanism where a new class is derived from an existing class.  A class may inherit or reuse attributes and methods of other class.  A class derived from another class is called a subclass or child class, whereas the class from which a subclass is derived is called a superclass or parent class. 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 28 Super class Child class Child class
  • 29. Copyright (c) SunilOS ( RAYS ) Technologies 29 Inheritance :Shape color :String borderWidth:int getColor():String setColor() getBorderWidth():int setBorderWidth() :Rectangle length :int width:int area() getLength() setLength() :Circle radius : int area() getRadius() setRadius() :Triangle base:int hight:int area() getBase() setBase() Circle c =new Circle(); c.getColor(); c.getBorderWidth(); c.area(); :object UML Notation 4-Jan-20
  • 30. Why Inheritance ?  When a class needs to define specialized behavior of a class then inheritance is required  For example Circle, Rectangle and Triangle are providing specialized behavior of Shape class.  Here Circle, Rectangle and Triangle are called specialized classes whereas Shape is called generic class  One class can inherit another class using following syntax: o class Circle(Shape):  By default object is root super class of all classes in python 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 30
  • 31. Shape class  class Shape: o def __init__(self, c, b):  self.color = c  self.borderWidth = b o def area(self):  return -1 o def setColor(self, c):  self.color = c o def getColor(self):  return self.color 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 31 :Shape color :String borderWidth:int getColor():String setColor() getBorderWidth():int setBorderWidth()
  • 32. Circle class  class Circle(Shape):  PI = 3.14  #c & b are optional  def __init__(self, r, c=“”, b=0):  self.radius = r  super(Circle,self).__init__(c,b)  def area(self): #override method  return self.radius*self.radius*Circle.PI  Create instance o c1 = Circle(2,'Red',5) o c2 = Circle(3,'Blue') o c3 = Circle(4) o print(c1.area()) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 32
  • 33. Rectangle Class  class Rectangle(Shape):  def __init__(self, length, width , c='', b=0):  self.length = length  self.width = width  super(Rectangle,self).__init__(c,b)   def area(self):  return self.length * self.length 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 33
  • 34. Triangle Class  class Triangle(Shape): o def __init__(self, base, height , c='', b=0):  self.base = base  self.height = height  super(Rectangle,self).__init__(c,b) o def area(self):  return (self.base * self.height) /2 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 34
  • 35. Type of inheritance 1. Single Inheritance 2. Multilevel Inheritance 3. Hierarchical Inheritance 4. Multi Inheritance 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 35 A B A B C A B C A B C
  • 36. Multiple Inheritance  Like C++, a class can be derived from more than one base classes in Python. This is called multiple inheritance  class Shape: o ..  class Design: o ..  class Circle(Shape, Design): o .. 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 36
  • 37. Method Overriding  Child classes can override parent class methods  Circle, Rectangle and Triangle child classes have overridden area()method of Shape class  class Shape: o def area(self):  return -1  class Rectangle(Shape): o def area(self):  return self.length * self.length 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 37
  • 38. Access Modifier  Python has three types of access modifiers o public, private, and protected.  Public variables can be accessed inside or outside the class  Private variables can only be accessed inside the class  Protected variables can be accessed within the same package  Variable name is prefixed by double underscore (__) to make it private  Variable name is prefixed by single underscore (_) to make it protected  Public variables do not have any prefixes  class Employee: o def __init__(self):  self.name = “Ram" #public  self._code = “E101” #protected  self.__salary= 25000 #private 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 38
  • 39. Abstract Classes 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 39
  • 40. Abstract class  Abstract classes are classes that contain one or more abstract methods  An abstract method is a method that is declared, but contains no implementation  Abstract classes may not be instantiated  Subclasses are required to provide implementations for the abstract methods  For example area() method in Shape class does not have implementation. Area implementation must be provided by child classes Circle, Rectangle and Triangle  Shape will be an abstract class because area()is an abstract method 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 40
  • 41. Create an abstract class  Python provides a module to define Abstract Base Classes (ABCs).  This module is called abc  You can import abc module using following command: o from abc import ABC, abstractmethod  Abstract class is inherited from ABC class and abstract method is annotated by @abstractmethod annotation o class Shape(ABC): o def __init__(self, c, b): o self.color = c o self.borderWidth = b o @abstractmethod o def area(self): o pass 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 41
  • 42. Child class  Child class must implement abstract methods otherwise child will become abstract  from abc import ABC, abstractmethod  class Shape(ABC):  @abstractmethod  def area(self):  pass  class Circle(Shape):  PI = 3.14  def area(self):  return self.radius * self.radius * Circle.PI  c = Circle(10,"Red",2)  print(c.area()) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 42
  • 43. Exception Handling 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 43 throw catch • Exception causes abnormal termination of program or wrong execution result. • Python provides an exception handling mechanism to handle exceptions. • Exception handling is done by try-except- else-finally blocks. • Exception raised in try block is caught by except block. • Block finally is optional and always executed.
  • 44. Exception Handling Exception is an error in a program execution that breaks the normal flow of program. When you handle these exceptions and execute an alternate path of program then it is called exception handling. Exceptions are handled by following blocks o try/except o try/finally 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 44
  • 45. try-except  a =4  b = 0  try:  c= a/b  print('C:',c)  except ZeroDivisionError:  print("check your dividend is Zero")  Block except can handle multiple exceptions. o except ex1,ex2,ex3 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 45
  • 46. Print exception message  try:  c= a/b  print('C:',c)  except ZeroDivisionError as e:  print(“Exception:", e) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 46
  • 47. try-except-else  a =4  b = 2  try:  c= a/b  print('C:',c)  except ZeroDivisionError:  print("check your division is Zero")  else: # it will be executed when no exception  print("Your division was greater than zero") 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 47
  • 48. try-finally  try:  c= a/b  print('C:',c)  except ZeroDivisionError as e:  print("Check your division is Zero", e)  finally:  print(“Always executed")  Finally block will be executed whether exception is occurred or not. 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 48
  • 49. Raise an Exception  You can raise your custom exception using raise statement  Raise statement throws instance of Exception class  try:  number = int(input("Enter your Number :"))  if number > 10:  raise Exception(‘invalid number')  except Exception as e:  print(e) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 49
  • 50. Custom Exception TODO 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 50
  • 51. Exception List 8 EOFError: Raised when there is no input from either the raw_input() or input() function and the end of file is reached. 9 ImportError: Raised when an import statement fails. 10 IndexError: Raised when an index is not found in a sequence. 11 KeyError: Raised when the specified key is not found in the dictionary. 12 NameError: Raised when an identifier is not found in the local or global namespace. 13 IOError: Raised when an input/ output operation fails, such as the print statement or the open() function when trying to open a file that does not exist. 14 RuntimeError: Raised when a generated error does not fall into any category. 15 NotImplementedError: Raised when an abstract method that needs to be implemented in an inherited class is not actually implemented. 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 51
  • 52. Exception List # Exception Name & Description 1 Exception :Base class for all exceptions 2 StopIteration :Raised when the next() method of an iterator does not point to any object. 3 ArithmeticError: Base class for all errors that occur for numeric calculation. 4 OverflowError: Raised when a calculation exceeds maximum limit for a numeric type. 5 FloatingPointError: Raised when a floating point calculation fails. 6 ZeroDivisionError: Raised when division or modulo by zero takes place for all numeric types. 7 AttributeError:Raised in case of failure of attribute reference or assignment. 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 52
  • 53. File IO 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 53
  • 54. File IO  Python provides basic functions to read and write a text and binary files.  Function open() is used to open a file into read or write mode. o file = open(“Hello.txt")  File can be opened in different mode like read, write, append etc. o file = open(“Hello.txt“,”w”)  A file can be closed by its close() method o file.close() 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 54
  • 55. File Info  Here is program to read file information o fo = open("Test.py", “rw”, 0) o print ("File Name: ", fo.name) o print ("Mode of Opening: ", fo.mode) o print ("Is Closed: ", fo.closed) o fo.close()  Parameters of open function are: o Name o Mode o Buffering 0: No 1: Yes 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 55
  • 56. Read from File Here is program that read entire text from file: o file = open(“Hello.txt") //open a file o text = file.read() # read all text o print(text) o file.close() # close the file o return Read binary data o bArray = file.read(10); 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 56
  • 57. Read Line by Line You can read file line by line using for loop o file = open(“Hello.txt") o for line in file: o print(line) o file.close() 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 57
  • 58. Write to a File Write into a file using write mode o file = open("Test.txt","w") o file.write("Hin") o file.write("This is Python file") o file.close() 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 58
  • 59. With Statement  It is used to manage the resources  It makes code more cleaner  It automatically closes file when block is finish  with open("Test.txt","w")as file: o file.write("Hin") o file.write("This is Python file") 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 59
  • 60. File Position  str = fo.read(10);  position = fo.tell();  position = fo.seek(0, 0)  import os  os.rename( "test1.txt", "test2.txt" )  os.remove("text2.txt") 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 60
  • 61. Mode of File Mode Description r Opens a file for reading only. (It's a default mode.) w Opens a file for writing. (If a file doesn't exist already, then it creates a new file, otherwise, it's truncate a file.) x Opens a file for exclusive creation. (Operation fails if a file does not exist in the location.) a Opens a file for appending at the end of the file without truncating it. (Creates a new file if it does not exist in the location.) t Opens a file in text mode. (It's a default mode.) b Opens a file in binary mode. + Opens a file for updating (reading and writing.) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 61
  • 62. Object Serialization  You may need to store an object into a file or send over the network that time you need to convert your object into byte stream, this is called serialization.  When you restore object from byte stream then it is called deserialization 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 62 Serialization Deserialization https://pmm.nasa.gov/education/water-cycle
  • 63. Object Serialization  The pickle module is used to serialize and de-serialize an object  Serializing process is called Pickling  De-serializing process is called Unpickling  Here we are storing employee object into emp.dat file  import pickle  class Employee:  def __init__(self,eno,ename):  self.eno=eno  self.ename=ename  e = Employee(1,'Mayank')  f = open('emp.dat','wb')  pickle.dump(e,f)  f.close() 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 63
  • 64. Unpickling import pickle f = open('emp.dat','wb’) e = pickle.load(f) f.close() print(e.name) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 64
  • 65. Concurrency and Theading 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 65
  • 66. Copyright (c) SunilOS ( RAYS ) Technologies 66 Process  A process has a self-contained execution environment.  A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space.  Python program is executed as a single process. 4-Jan-20
  • 67. Copyright (c) SunilOS ( RAYS ) Technologies 67 Concurrency vs. Parallelism CPU CPU1 CPU2 4-Jan-20
  • 68. Copyright (c) SunilOS ( RAYS ) Technologies 68 Thread  Threads are sometimes called lightweight processes.  Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.  Threads exist within a process  Every process (application) has at least one thread.  Threads share resources of their process. Resource are memory and open files.  Each thread is associated with an instance of the class Thread 4-Jan-20
  • 69. Copyright (c) SunilOS ( RAYS ) Technologies 69 Threads and Processes 4-Jan-20
  • 70. Copyright (c) SunilOS ( RAYS ) Technologies 70 Multitasking & Multithreading  Multitasking refers to a computer's ability to perform multiple jobs concurrently. Multitasking means more than one programs are running together on a single machine.  A thread is a single sequence of execution within a program.  Multithreading refers to multiple threads of control within a single program. Each program can run multiple threads of control within it, e.g., Web Browser. 4-Jan-20
  • 71. HelloWithoutThread  Let’s create two functions hello() and hi(). Run both functions without thread  def hello():  for i in range(15):  print ( 'Hello ',i)  def hi():  for i in range(15):  print ( 'Hi ‘,i)  hello()  hi()  Both functions will be executed sequentially Copyright (c) SunilOS ( RAYS ) Technologies 714-Jan-20
  • 72. HelloWithoutThread output  Hello 0  Hello 1  Hello 2  …  Hello 14  Hi 0  Hi 1  Hi 2  ..  Hi 14 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 72
  • 73. Hello With Thread  Let’s create two threads and run hello() and hi()functions inside thread.  import threading  from threading import *  ..  t1 = threading.Thread(target = hello)  t2 = threading.Thread(target = hi)  #Start threads  t1.start()  t2.start()  Both functions will be executed concurrently Copyright (c) SunilOS ( RAYS ) Technologies 734-Jan-20
  • 74. Hello With Thread output  Hello 0  Hello 1  Hello 2  Hi 0  Hello 3  …  Hi 10  Hello 14  Hi 11  Hi 13  Hi 14 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 74
  • 75. Copyright (c) SunilOS ( RAYS ) Technologies 75 Thread 4-Jan-20
  • 76. Raktabija 1. Raktabija had a capability to create another Raktbija by his single drop of blood. 2. Created Raktabija will be equally powerful, and can consume same kind of resources and work concurrently. 3. If one Raktabija dies another will remain active and live. 1. Likewise a Thread can create another thread. 2. Created Thread will be equally powerful, and can consume same kind of resources and work concurrently. 3. If one thread dies, other will remain active in memory. Copyright (c) SunilOS ( RAYS ) Technologies 76 http://en.wikipedia.org/wiki/Raktavija 4-Jan-20
  • 77. Copyright (c) SunilOS ( RAYS ) Technologies 77 Creating Threads  There are two ways to create a Thread o Create a function and use Thread object to run this function inside thread o Inherit Thread class and override run() method  You need to import threading module to make a thread o import threading o from threading import * 4-Jan-20
  • 78. Function as thread  Create a function and pass its name to target attribute of Thread constructor  import threading  from threading import *  def hello():  for i in range(15):  print ( 'Hello’, i )  #create thread  t1 = threading.Thread(target = hello)  #Start threads  t1.start() 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 78
  • 79. Parametrized function as thread  Pass argument array to args attribute of Thread constructor  def hello(name):  for i in range(15):  print ( name , i)  t3 = threading.Thread(target=hello, args=('Ram',))  t4 = threading.Thread(target=hello, args=('Shyam',)) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 79
  • 80. Inherit Thread class  Inherit Thread class and override run() method  class Hi(Thread):  def run(self):  for i in range(15):  print("Hi", i )  #Create thread  t1= Hi()  #Start thread  t1.start() 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 80
  • 81. Daemon Threads  Daemon threads are “background” threads, that provide services to other threads, e.g., the garbage collection thread  Program will not exit if non-Daemon threads are executing  Program will exit if only Daemon threads are executing  You can make a daemon thread by  t1 = threading.Thread(target=hello, daemon=True) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 81
  • 82. Thread Constructor  class threading.Thread (group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)  group should be None; reserved for future use  target is the callable function  args is the argument tuple for the target function  name of the thread  kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.  daemon if given True, it makes thread daemon 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 82
  • 83. Thread handling  threading.active_count() : returns count of active alive threads  threading.current_thread(): returns current thread object  threading.get_ident(): returns id of the current thread  threading.enumerate(): return a list of all Thread objects currently alive  threading.main_thread(): return of main thread that started Python interpreter  threading.TIMEOUT_MAX: The maximum value allowed for the timeout to a blocking function 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 83
  • 84. Synchronization 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 84
  • 85. Synchronization  Synchronisation is applied on objects or functions, those are shared by concurrent threads  Syncronization make sure that a shared resource can be accessed by only one thread at a time  Syncronized resources are accessed sequencially by concurrent threads 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 85
  • 86. Race condition Syncronization causes race condition among Threads Threading module provides a Lock class to deal with the race condition Following are methods of Lock class: o lock = threading.Lock(): It creates a lock object o lock.acquire(): It acquires the lock for current thread o lock.release(): It releases the lock 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 86
  • 87. Account Class  Lets create an Account class which will be accessed by concurrent threads o class Account: o balance =0 o def get_balance(self): o sleep(2) o return self.balance o def set_balance(self, amount): o sleep(2) o self.balance = amount o def diposite(self, amount): o bal = self.get_balance() o self.set_balance(bal + amount)  It is assumed that set and get balance operation takes 2 seconds to execute 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 87
  • 88. Racing Thread  class Racing(Thread):  account: Account  name = ""  def __init__(self,account, name):  super().__init__()  self.account = account  self.name = name  def run(self):  for i in range(5):  self.account.diposite(100)  print( self.name, self.account.get_balance())  t1 = Racing(acc, "Ram")  t2 = Racing(acc, "Shyam")  t1.start()  t2.start() 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 88 • Racing thread is depositing Rs 1000 five times in the account • Two threads are started and both are racing to deposit amount
  • 89. Output  Shyam 100  Ram 100  Shyam 200  Ram 200  Ram 300  Shyam 300  Ram 400  Shyam 400  Shyam 500  Ram 500 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 89
  • 90. Synchronize deposit  class Account:  balance =0  def __init__(self):  self.lock = threading.Lock()  def get_balance(self):  sleep(2)  return self.balance  def set_balance(self, amount):  sleep(2)  self.balance = amount   def diposite(self, amount):  self.lock.acquire()  bal = self.get_balance()  self.set_balance(bal + amount)  self.lock.release() 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 90
  • 91. Output  Ram 100  Shyam 200  Ram 300  Shyam 400  Ram 500  Shyam 600  Ram 700  Shyam 800  Ram 900  Shyam 1000 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 91
  • 92.  Emails are sent by SMTP protocol  Module smtplib is used to send an email  You can send plain text or HTML text in email body  You can attach files with emails  Following SMTP servers can be used to send an email o GMail o Yahoo o Hotmail o Etc. Email 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 92
  • 93. Send Plain Text in Email  import smtplib  smtp_server = "smtp.gmail.com"  port = 587 # For TLS  sender_email = "webmaster@sunrays.co.in"  password = input("Enter password and press enter: ")  receiver_email = “myfriend@gmail.com"  message = """From: Sunil Sahu <webmaster@nenosystems.com>  CC: sunil.sahu@nenosystems.com  Subject : Hi from python  <H1>HI this is my first email from Python.</H1>  """  smtp = smtplib.SMTP(smtp_server,port)  smtp.starttls() #Enable transport layer security  smtp.login(sender_email,password)  smtp.sendmail(sender_email, receiver_email, message)  smtp.quit() 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 93
  • 94. Secure Email  An SMTP connection is secured and encrypted so that message and login credentials are not easily accessed by others  SSL (Secure Sockets Layer) and TLS (Transport Layer Security) are two protocols that can be used to encrypt an SMTP connection.  Gmail SMTP server provides 465 port for SSL and 587 port for TLS connection  There are two ways to secure connection  Making SSL connection  connection = smtplib.SMTP_SSL(smtp_server, 465)  connection.login(sender_email,password)  Enable TLS by calling method smtplib.starttls()  connection = smtplib.SMTP(smtp_server, 587)  connection.starttls()  connection.login(sender_email,password) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 94
  • 95. Email Subject & Body  Email contains subject and body text message  Subject and body text are delimited by two new line characters (nn) and prefixed by “Subject : ” word o subject = "First Email" o text = "How are you ?" o body = "Subject: " + subject + " nn " + text o connection.sendmail(sender_email, receiver_email, body) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 95
  • 96. HTML content  Python provides MIME (Multipurpose Internet Mail Extensions) Multipart emails.  Mutiple part email contains mutiple parts in email like plain text, html text, files etc.  It is used to send HTML emails and file attachements  Module email.mime provides classes to make mutiple part emails. o import smtplib o from email.mime.multipart import MIMEMultipart o from email.mime.text import MIMEText o from email.mime.base import MIMEBase o from email import encoders 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 96
  • 97. Send HTML Email  text = “Hi How are you”  html = "<html><body><h1>Hi, How are you</h1></body></html>   msg = MIMEMultipart() # instance of MIMEMultipart  msg['From'] = sender_email # storing the senders email address  msg['To'] = receiver_email # storing the receivers email address  msg['Subject'] = "This is Mutipart email" # storing the subject  msg.attach(MIMEText(text, 'plain')) #plain text part  msg.attach(MIMEText(html, 'html')) #html text part   s = smtplib.SMTP('smtp.gmail.com', 587)  s.starttls()  s.login(sender_email, password)  s.sendmail(sender_email, receiver_email, msg.as_string())  s.quit() 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 97
  • 98. Attach A File  In multipart email you can also attach one or more files as a part.  filename = "SimpleMail.py"  with open(filename, "rb") as attachment:  # instance of MIME Base and named as p  p = MIMEBase('application', 'octet-stream')  # To change the payload into encoded form  p.set_payload((attachment).read())  # encode into base64  encoders.encode_base64(p)  p.add_header('Content-Disposition’ , "attachment; filename= %s" % filename)  # attach the instance 'p' to instance 'msg'  msg.attach(p) 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 98
  • 99. Tkinter 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 99
  • 100. Networking 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 100
  • 101. Database Connectivity 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 101
  • 102. DJango 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 102
  • 103. References  https://docs.python.org/3/library/threading.html  https://realpython.com/python-send-email/  https://likegeeks.com/python-gui-examples-tkinter-tutorial/ 4-Jan-20 Copyright (c) SunilOS ( RAYS ) Technologies 103

Editor's Notes

  1. 1
  2. 1/4/2020
  3. 1/4/2020
  4. 1/4/2020
  5. 1/4/2020
  6. 1/4/2020
  7. 1/4/2020
  8. 1/4/2020
  9. 1/4/2020
  10. 1/4/2020
  11. 1/4/2020