The document discusses Python modules and classes. It explains that a module is a .py file that can contain functions, classes, and variables. A module can be imported and its elements used in another file. A class defines the structure of an object with attributes like name and methods like setName(). Inheritance allows a child class to inherit attributes and methods from a parent class, with the ability to override methods. The document provides examples of defining classes like Shape and inheriting from it to create child classes like Circle.
Application One application ismade 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 isa 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 isUserService 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 canimport 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 … importstatement 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 OrientedProgramming 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 Applicationruntime 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 ofan 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 isthe 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
Object An objectis 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
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
Test Person Letscreate 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 classhas 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 isa 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 Aclass 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 objectis 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__ Anobject 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 Youcan 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 allrelated 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 isa 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
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 classShape: 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 classCircle(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
Triangle Class classTriangle(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 LikeC++, 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 Childclasses 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 Pythonhas 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 class Abstractclasses 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 abstractclass 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 Childclass 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 isan 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
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
Exception List 8 EOFError: Raisedwhen 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 # ExceptionName & 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 Pythonprovides 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 Hereis 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 Hereis 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 byLine 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 aFile 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 Itis 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 ModeDescription 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 Youmay 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 Thepickle 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
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
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 createtwo 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 Hello0 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 Threadoutput 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
Raktabija 1. Raktabija hada 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 asthread 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 Daemonthreads 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 classthreading.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
Synchronization Synchronisation isapplied 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 causesrace 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 Letscreate 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 classRacing(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
Emails aresent 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 Textin 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 AnSMTP 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 Pythonprovides 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