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.
The document discusses exception handling in Java. It defines exceptions as abnormal conditions that occur during program execution. Java provides keywords like try, catch, throw and finally to handle exceptions. The document explains different types of exceptions like checked exceptions that must be handled and unchecked exceptions. It also covers how to define custom exception classes, throw and propagate exceptions, and use multiple catch blocks to handle different exception types.
This document provides an overview of unsupervised machine learning and reinforcement learning. It discusses unsupervised learning, including clustering methods like k-means. It then explains reinforcement learning concepts such as the agent, environment, actions, states, rewards, and policy. Reinforcement learning is goal-oriented learning based on interaction. Q-learning and Markov decision processes are introduced as reinforcement learning models. Applications include using the Gym library in Python to model environments like cart pole.
The document discusses variables and operators in Java. It defines variables as containers that store data like numbers and letters, and notes that data types determine what values can be stored. It then covers various data types including primitive types like int and float, and reference types like Strings and Arrays. The document also discusses operators like arithmetic, logical, and assignment operators. It provides examples of declaring and using variables and operators in Java code.
This document discusses Java 8 features including anonymous functions, functional interfaces, lambda expressions, default and static methods, and forEach(). Anonymous functions allow defining functions without naming them. Functional interfaces specify a single abstract method that can be implemented using lambda expressions. Default and static methods allow adding new methods to interfaces without breaking existing code. The forEach() method is used to iterate over elements of a collection and can take a lambda expression.
The document discusses Structured Query Language (SQL) and Java Database Connectivity (JDBC). It provides examples of using SQL statements like SELECT, INSERT, UPDATE, DELETE to query and manipulate data in database tables. It also demonstrates how to connect to databases like MySQL from Java using JDBC, execute SQL queries to retrieve and manipulate data, handle transactions and exceptions. Key classes discussed are Connection, Statement, PreparedStatement, CallableStatement and their methods.
The document discusses threading and concurrency in Java. It begins with an introduction to single-threaded versus multi-threaded programming. It then covers key threading concepts like creating threads by extending Thread or implementing Runnable, starting threads, thread scheduling, priorities, and synchronization to avoid race conditions. Examples are provided to demonstrate creating and running threads concurrently. The last sections discuss thread states, methods, daemon threads, and different types of synchronization.
The document provides information on object-oriented programming concepts like classes, objects, encapsulation, inheritance and polymorphism. It discusses Java primitive data types like boolean, char, byte etc. It also covers defining custom classes with attributes and methods, creating objects, constructors, access modifiers, inheritance and polymorphism. The key concepts of OOP like encapsulation, inheritance and polymorphism are explained with examples.
The document provides information about the C programming language. It discusses that C is a procedural language that is case sensitive and can be compiled on various platforms. It also provides examples of C programs, including printing "Hello World", using data types like int and float, and control structures like if-else statements and for loops. The document contains code snippets to demonstrate basic C programming concepts.
The document discusses Log4J, a logging framework for Java applications. It describes how Log4J can be used to log messages to different targets like the console, files, and databases. Log messages are categorized by level (debug, info, warn, error, fatal) and Log4J provides methods to log each level. Appenders define the target for log messages and common appenders include the ConsoleAppender and FileAppender. The configuration file log4j.properties is used to define appenders, message layout, and logging levels for different environments like development, testing, and production.
This document provides information on processes, threads, concurrency, and parallelism in Java. It discusses that processes have separate memory spaces while threads within the same process share memory. It describes how to create threads by extending Thread or implementing Runnable. It also covers thread states, scheduling, priorities, and daemon threads.
Hibernate is an object-relational mapping tool that allows Java objects to be persisted to a relational database. It provides transparent persistence by handling all database operations like insert, update, delete, and retrieval. Hibernate sits between the Java application and database, mapping objects to database tables and allowing developers to work with objects rather than directly with SQL statements. Configuration files define the mappings between Java classes and database tables. Hibernate uses these mappings to automatically generate SQL to load and store objects.
This document discusses Java input/output (IO) streams and serialization. It covers reading and writing text and binary files using classes like FileReader, FileWriter, ObjectInputStream and ObjectOutputStream. It also discusses reading from the keyboard, reading file attributes, serialization which converts an object to bytes, deserialization which converts bytes to an object, and using the Externalizable interface to customize serialization. The goal is to provide an overview of performing IO operations and serialization in Java.
This document provides an overview of JUnit, a unit testing framework for Java. It discusses how JUnit allows developers to write repeatable tests and test classes in a way that each test can run independently without affecting other tests. The document demonstrates how to write test cases using JUnit annotations and assertions for an AccountService class. It also covers test suites that group multiple test cases, the JUnit testing lifecycle using annotations, and dependencies needed to use JUnit.
Resource bundles are used to support internationalization (i18n) and externalize configuration parameters from code. They work by storing configurable key-value pairs in properties files that can be read at runtime. The document discusses how to create properties files, read values from them using the ResourceBundle class, and support multiple languages by creating localized properties files for different locales. It also explains the Locale class used to retrieve the correct localized properties file based on language, country, and variant settings.
This document provides an introduction to the Java programming language. It discusses that Java is an object-oriented programming language used to write computer programs. It also describes the basic elements of the Java language including commands, variables, data types, control statements, and functions/methods. Additionally, it explains that the basic building block of Java is the class, and that a Java program or application consists of multiple classes organized into packages.
The document discusses input/output streams in Java. It covers:
- Different types of data storage including transient RAM and persistent storage like disks.
- I/O sources and destinations like consoles, disks, networks etc. and how streams represent sequential bytes to abstract I/O details.
- Common Java I/O stream classes like FileReader, FileWriter, InputStream and OutputStream for reading/writing text and binary data from files.
- Using File class to represent files and directories with methods to check attributes, read content and manipulate files.
This document provides an overview of Java basics including:
- Java is an object-oriented programming language like C++.
- The basic unit in Java is the object, which contains both state in the form of variables and behavior in the form of methods.
- Classes define the structure and behavior of objects through methods and variables. The main method is required to execute a Java program.
The document provides information on object-oriented programming concepts in Java including classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It defines classes like Shape, Rectangle, Circle and Triangle to demonstrate these concepts. It also discusses Java data types, constructors, access modifiers, interfaces and abstract classes.
1. CSS (Cascading Style Sheets) is a language used to define the style and layout of web pages. CSS can be applied internally, inline, or through external style sheets.
2. There are different types of CSS selectors including tag selectors, ID selectors, and class selectors that allow styles to be applied to specific HTML elements. Common CSS properties define colors, fonts, spacing, and layout.
3. CSS3 introduces newer specifications like rounded corners, shadows, gradients, transitions, and transformations that expand on the original CSS standards. Features like custom fonts, multi-column layout, flexible box and grid layouts add additional styling capabilities.
This document provides an overview of JSP/Servlet architecture. It describes how a web request is handled from the browser to the web server and JSP/Servlet container. It then discusses key components like servlets, JSPs, the request and response objects. It provides examples of basic servlet and JSP code to output text and access request parameters. It also covers servlet configuration, mappings, and the use of forwards and redirects.
This class is abstract but it does not provide implementation of abstract method print(). An abstract class must be subclassed and the abstract methods must be implemented in the subclass. We cannot create an object of an abstract class directly, it has to be through its concrete subclass.
The document provides an overview of lecture 03 on objects and classes in Java, including reviewing basic concepts, declaring and using classes, implementing inheritance, and discussing abstract classes and interfaces. It also includes examples of declaring classes, using constructors and methods, and implementing inheritance and polymorphism. The lecture aims to help students understand object-oriented concepts in Java like classes, objects, inheritance and polymorphism.
This document discusses object-oriented programming concepts in Python including:
- Classes define templates for objects with attributes and methods. Objects are instances of classes.
- The __init__ method initializes attributes when an object is constructed.
- Classes can make attributes private using double underscores. Encapsulation hides implementation details.
- Objects can be mutable, allowing state changes, or immutable like strings which cannot change.
- Inheritance allows subclasses to extend and modify parent class behavior through polymorphism.
The document provides information about object-oriented programming concepts in C#, including classes, objects, methods, constructors, and constructor overloading. It consists of a lab manual with 16 topics on OOP concepts. Each topic is presented on its own page and includes definitions, explanations, examples, and code snippets in C# to illustrate the concept. Constructor overloading allows defining multiple constructors with the same name but different parameters to initialize objects in different ways.
This document provides an overview of object-oriented programming concepts including classes, objects, encapsulation and abstraction. It begins by describing the objectives of learning OOP which are to describe objects and classes, define classes, construct objects using constructors, access object members using dot notation, and apply abstraction and encapsulation. It then compares procedural and object-oriented programming, noting that OOP involves programming using objects defined by classes. Key concepts covered include an object's state consisting of data fields and behavior defined by methods. The document demonstrates defining classes, creating objects, accessing object members, and using private data fields for encapsulation.
OOP stands for Object-Oriented Programming. It involves creating objects that contain both data and methods. Classes act as templates for objects and define their attributes and behaviors. Some advantages of OOP include reusability, organization, and reduced repetition of code. Classes contain fields to store data and methods to perform actions on that data. Objects are instances of classes that inherit all fields and methods. Constructors initialize objects and can set initial field values. Arrays can store multiple objects. Dynamic arrays allow adding elements at runtime. Partial classes allow splitting a class definition across multiple files.
The document discusses object-oriented programming in Python. It defines key OOP concepts like classes, objects, and methods. It provides examples of defining classes and methods in Python. It also covers inheritance, polymorphism, and data abstraction in OOP. Database programming in Python is also discussed, including connecting to databases and performing CRUD operations using the Python DB API.
The document provides an overview of object-oriented programming concepts in Python including defining classes, inheritance, methods, and data structures. Some key points:
- Classes define user-created data types that bundle together data (attributes) and functions (methods) that work with that data. Objects are instances of classes.
- Methods are defined within classes and must have "self" as the first argument to access attributes. The __init__ method serves as a constructor.
- Inheritance allows subclasses to extend existing classes, redefining or calling parent methods.
- Python supports lists, tuples, dictionaries, sets and other data structures that can be used to store and organize data. Lists are mutable while tuples are immutable.
This document discusses Python modules, classes, inheritance, and properties. Some key points:
- Modules allow the organization of Python code into reusable libraries by saving code in files with a .py extension. Modules can contain functions, variables, and be imported into other code.
- Classes are templates that define the properties and methods common to all objects of a certain kind. The __init__() method initializes new objects. Inheritance allows child classes to inherit properties and methods from parent classes.
- Properties provide a way to control access to class attributes, allowing them to be accessed like attributes while hiding the implementation details behind getter and setter methods.
This document provides an overview of object-oriented programming (OOP) concepts in C++. It defines key OOP concepts like class, object, inheritance, encapsulation, abstraction, polymorphism, and overloading. It provides examples to illustrate class and object, inheritance with different types, encapsulation by hiding data, and function overloading. The document was prepared by a trainee as part of a mentoring program and provides contact information for the training organization.
This document provides an overview of object-oriented programming concepts in Python including classes, objects, inheritance, polymorphism and data hiding. It defines key OOP terms like class, object, method, and inheritance. It also demonstrates how to define classes with attributes and methods, create object instances, and extend functionality via inheritance. The document shows how operators and methods can be overloaded in classes.
C++ is an object-oriented programming language that is an incremented version of C with classes added. Some key differences between C and C++ are that C++ uses object-oriented programming with classes that can contain both data and functions, while C focuses more on procedures/functions and allows any function to access data. The document then discusses the basic concepts of object-oriented programming in C++ including classes, objects, polymorphism, inheritance, encapsulation, and data abstraction. It provides examples of classes, objects, reference variables, default arguments, and dynamic memory allocation in C++.
Python classes allow for the creation of object-oriented programming through defining blueprints for objects with shared attributes and behaviors. Classes are created using the class keyword and contain attributes like variables and methods like functions. Objects are instantiated from classes and can access both class level and instance level attributes. Key concepts covered include inheritance, encapsulation, polymorphism, and special methods.
Python classes allow for the creation of object-oriented programming in Python. Classes define blueprints for objects with shared attributes and behaviors. Key aspects of classes include defining attributes and methods, constructing objects from classes, inheritance that allows subclasses to extend parent classes, and special methods that enable built-in behaviors. Classes are a fundamental part of Python that enable code reuse and organization.
The document provides an overview of object-oriented programming (OOP) concepts using PHP including classes, objects, properties, methods, encapsulation, inheritance, polymorphism, and magic methods. It defines key OOP terms like class, object, constructor, destructor, and visibility scopes. The document also discusses benefits of OOP like code reuse and data hiding.
The document provides an introduction to object-oriented programming concepts in Python using PyTorch examples. It discusses key object-oriented programming concepts like classes, instances, attributes, encapsulation, inheritance and polymorphism. It also summarizes some example PyTorch code to demonstrate concepts like classes, methods, inheritance and polymorphism in an object-oriented deep learning context.
This document provides an overview of object-oriented programming concepts like classes, objects, encapsulation, inheritance, polymorphism, and data hiding. It explains key OOP concepts like classes define custom data types with attributes and methods, objects are instances of classes, encapsulation groups related data and code, inheritance creates specialized classes from general classes, polymorphism allows one interface for multiple forms. It also discusses concepts like abstract classes, interfaces, constructors, destructors, operator overloading and access modifiers for data hiding. Overall, the document serves as an introduction to fundamental OOP principles in C++.
Class 7 - PHP Object Oriented ProgrammingAhmed Swilam
This document provides an overview of object-oriented programming (OOP) concepts in PHP. It discusses previous programming trends like procedural and structured languages. It then covers key OOP concepts like classes, objects, inheritance, polymorphism, and abstraction. Specific PHP OOP features are explained like class diagrams, access modifiers, constructors, destructors, static members, and class constants. Examples are provided to demonstrate classes, inheritance, polymorphism, abstract classes, interfaces, and exceptions. The document concludes with an assignment to model person, student, and teacher relationships using PHP classes.
The document discusses object-oriented programming concepts like classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It provides examples of defining classes like Shape, Rectangle, Circle etc. with attributes and methods. It also covers topics like constructors, access modifiers, static vs instance members, method overriding and overloading for polymorphism. The document explains how inheritance allows child classes to extend parent classes and abstract classes/methods that are implemented in child classes.
This document discusses concurrency and threads in Java. It begins by explaining how to create threads using the Thread class or Runnable interface. It then covers thread states, scheduling, and synchronization to prevent race conditions. Key points include how threads can run concurrently but share resources like memory, the use of synchronized methods to allow only one thread access at a time, and monitors that control access to objects.
This document provides an overview of exception handling in Java, including try/catch blocks, checked and unchecked exceptions, custom exceptions, and exception propagation. It defines exceptions as abnormal code conditions, explains how to handle exceptions with try/catch/finally, and covers exception hierarchies, multiple catch blocks, and system-defined vs. programmer-defined exceptions.
Pandas is an open source Python library that provides data structures and data analysis tools for working with tabular data. It allows users to easily perform operations on different types of data such as tabular, time series, and matrix data. Pandas provides data structures like Series for 1D data and DataFrame for 2D data. It has tools for data cleaning, transformation, manipulation, and visualization of data.
This document provides an overview of Angular, including:
- Angular is a JavaScript framework used to build client-side applications with HTML. Code is written in TypeScript which compiles to JavaScript.
- Angular enhances HTML with directives, data binding, and dependency injection. It follows an MVC architecture internally.
- Components are the basic building blocks of Angular applications. Modules contain components and services. Services contain reusable business logic.
- The document discusses Angular concepts like modules, components, data binding, services, routing and forms. It provides examples of creating a sample login/welcome application in Angular.
The document provides an overview of C# programming concepts including data types, variables, operators, and functions. Some key points:
- C# is a general-purpose programming language that uses basic data types like integers, floats, characters, and booleans. It supports derived data types and built-in types as objects.
- Almost every C# program must have one Main() function, which serves as the entry point. The Main() function and other functions use braces to delimit code blocks.
- Variables are declared with a data type and can be assigned values. C# distinguishes between value types and reference types. Operators are used to perform computations on variables.
- Functions, classes,
This document provides an overview of C# programming basics, including:
- C# is an object-oriented language where the basic unit is a class containing methods and variables.
- A C# program consists of at least one class that must contain a Main method, which acts as the program entry point.
- The document discusses basic C# concepts like variables, data types, operators, conditional statements, loops, methods, and arrays.
- It also covers how to compile and run a simple "Hello World" C# program, and provides examples of different programming constructs.
Raystec is an IT training and staffing company established in 2006 that operates in multiple Indian cities. It aims to provide highly trained IT professionals to companies by offering training courses on various technologies like Java, Android, Spring, Hadoop, and soft skills. Some of their clients include large companies and thousands of their trainees have received average placements of Rs. 5 lakh per year. Their management has over 20 years experience in open source technologies and executing enterprise projects. Contact details are provided for their main office in Indore and branch in Pune.
C++ is an object-oriented programming language that is based on classes and objects. A C++ program is made up of classes, which contain methods and variables. The basic building block of a C++ program is the class. A class defines the structure and behavior of an object. Objects are instances of classes that contain their own set of properties and behaviors. The main() method acts as the entry point for program execution. C++ supports features like functions, arrays, control statements, strings and more.
The document discusses graphical user interface (GUI) components in Java. It covers topics like basic GUI units like frames and panels, common Swing components like JFrame, JButton, JTextField, layout managers, event handling using listeners, and examples of creating simple GUI applications in Java. Key concepts explained include the component hierarchy in Swing, commonly used layouts like FlowLayout, BorderLayout and GridLayout, and how to add listeners for events like button clicks and window closing. Code samples are provided to demonstrate creating frames, adding components, setting layouts and handling events.
Ardra Nakshatra (आर्द्रा): Understanding its Effects and RemediesAstro Pathshala
Ardra Nakshatra, the sixth Nakshatra in Vedic astrology, spans from 6°40' to 20° in the Gemini zodiac sign. Governed by Rahu, the north lunar node, Ardra translates to "the moist one" or "the star of sorrow." Symbolized by a teardrop, it represents the transformational power of storms, bringing both destruction and renewal.
About Astro Pathshala
Astro Pathshala is a renowned astrology institute offering comprehensive astrology courses and personalized astrological consultations for over 20 years. Founded by Gurudev Sunil Vashist ji, Astro Pathshala has been a beacon of knowledge and guidance in the field of Vedic astrology. With a team of experienced astrologers, the institute provides in-depth courses that cover various aspects of astrology, including Nakshatras, planetary influences, and remedies. Whether you are a beginner seeking to learn astrology or someone looking for expert astrological advice, Astro Pathshala is dedicated to helping you navigate life's challenges and unlock your full potential through the ancient wisdom of Vedic astrology.
For more information about their courses and consultations, visit Astro Pathshala.
Integrated Marketing Communications (IMC)- Concept, Features, Elements, Role of advertising in IMC
Advertising: Concept, Features, Evolution of Advertising, Active Participants, Benefits of advertising to Business firms and consumers.
Classification of advertising: Geographic, Media, Target audience and Functions.
Understanding and Interpreting Teachers’ TPACK for Teaching Multimodalities i...Neny Isharyanti
Presented as a plenary session in iTELL 2024 in Salatiga on 4 July 2024.
The plenary focuses on understanding and intepreting relevant TPACK competence for teachers to be adept in teaching multimodality in the digital age. It juxtaposes the results of research on multimodality with its contextual implementation in the teaching of English subject in the Indonesian Emancipated Curriculum.
(T.L.E.) Agriculture: Essentials of GardeningMJDuyan
(𝐓𝐋𝐄 𝟏𝟎𝟎) (𝐋𝐞𝐬𝐬𝐨𝐧 𝟏.𝟎)-𝐅𝐢𝐧𝐚𝐥𝐬
Lesson Outcome:
-Students will understand the basics of gardening, including the importance of soil, water, and sunlight for plant growth. They will learn to identify and use essential gardening tools, plant seeds, and seedlings properly, and manage common garden pests using eco-friendly methods.
No, it's not a robot: prompt writing for investigative journalismPaul Bradshaw
How to use generative AI tools like ChatGPT and Gemini to generate story ideas for investigations, identify potential sources, and help with coding and writing.
A talk from the Centre for Investigative Journalism Summer School, July 2024
Views in Odoo - Advanced Views - Pivot View in Odoo 17Celine George
In Odoo, the pivot view is a graphical representation of data that allows users to analyze and summarize large datasets quickly. It's a powerful tool for generating insights from your business data.
The pivot view in Odoo is a valuable tool for analyzing and summarizing large datasets, helping you gain insights into your business operations.
Credit limit improvement system in odoo 17Celine George
In Odoo 17, confirmed and uninvoiced sales orders are now factored into a partner's total receivables. As a result, the credit limit warning system now considers this updated calculation, leading to more accurate and effective credit management.
How to Show Sample Data in Tree and Kanban View in Odoo 17Celine George
In Odoo 17, sample data serves as a valuable resource for users seeking to familiarize themselves with the functionalities and capabilities of the software prior to integrating their own information. In this slide we are going to discuss about how to show sample data to a tree view and a kanban view.
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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