SlideShare a Scribd company logo
PYTHON PROGRAMMING
UNIT IV
PROF.AJAY PASHANKAR
ASSISTANT PROFESSOR DEPARTMENT OF CS & IT
K.M.AGRAWAL COLLEGE KALYAN
www.profajaypashankar.com
 Regular Expressions :
 Concept of regular expression :
 A regular expression is a special sequence of characters that helps you match or find other
strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are
widely used in UNIX world.
 The module re provides full support for Perl-like regular expressions in Python. The re module
raises the exception re.error if an error occurs while compiling or using a regular expression.
 We would cover two important functions, which would be used to handle regular expressions.
Nevertheless, a small thing first: There are various characters, which would have special
meaning when they are used in regular expression. To avoid any confusion while dealing with
regular expressions, we would use Raw Strings as r'expression'.
 2)Various types of regular expressions:
 Basic patterns that match single chars
 • a, X, 9, < -- ordinary characters just match themselves exactly.
 • . (a period) -- matches any single character except newline 'n'
 • w -- matches a "word" character: a letter or digit or underbar [a-zA-Z0- 9_].
 • W -- matches any non-word character.
 • b -- boundary between word and non-word
 • s -- matches a single whitespace character -- space, newline, return, tab
 • S -- matches any non-whitespace character.
 • t, n, r -- tab, newline, return
 • d -- decimal digit [0-9]
 • ^ = matches start of the string
 • $ = match the end of the string
 •  -- inhibit the "specialness" of a character.
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
 Using match function.:
 This function attempts to match RE pattern to string with optional flags. Here is the syntax for
this function-
 re.match(pattern, string, flags=0)
The re.match function returns a match object on success, None on failure. We use
group(num) or groups() function of match object to get matched expression.
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
 Classes and Objects:
 Python is an object-oriented programming language, which means that it provides features
that support object-oriented programming (OOP).
 Object-oriented programming has its roots in the 1960s, but it wasn’t until the mid 1990s that it
became the main programming paradigm used in the creation of new software.
 It was developed as a way to handle the rapidly increasing size and complexity of software
systems, and to make it easier to modify these large and complex systems over time. Up to this
point we have been writing programs using a procedural programming paradigm.
 In procedural programming the focus is on writing functions or procedures which operate on
data. In object-oriented programming the focus is on the creation of objects which contain both
data and functionality together.
 Overview of OOP (Object Oriented Programming):
 a. Class: A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class variables and
instance variables) and methods, accessed via dot notation.
 b. Class variable: A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables are not used as
frequently as instance variables are.
 c. Data member: A class variable or instance variable that holds data associated with a class
and its objects.
 d. Function overloading: The assignment of more than one behavior to a particular function.
The operation performed varies by the types of objects or arguments involved.
 e. Instance variable: A variable that is defined inside a method and belongs only to the
current instance of a class.
 f. Inheritance: The transfer of the characteristics of a class to other classes that are derived
from it.
 g. Instance: An individual object of a certain class. An object obj that belongs to a class Circle,
for example, is an instance of the class Circle.
 h. Instantiation: The creation of an instance of a class.
 i. Method : A special kind of function that is defined in a class definition.
 j. Object: A unique instance of a data structure that is defined by its class. An object comprises
both data members (class variables and instance variables) and methods.
 k. Operator overloading: The assignment of more than one function to a particular operator.

 Class Definition:
 The class statement creates a new class definition. The name of the class immediately follows the keyword
class followed by a colon as follows-
 The variable empCount is a class variable whose value is shared among all the instances of a in this class.
This can be accessed as Employee.empCount from inside the class or outside the class.
 • The first method init () is a special method, which is called class constructor or initialization method that
Python calls when you create a new instance of this class.
 • You declare other class methods like normal functions with the exception that the first argument to each
method is self. Python adds the self argument to the list for you; you do not need to include it when you
call the methods.
 Creating Objects:
 To create instances of a class, you call the class using class name and pass inwhatever arguments its init
method accepts.
 This would create first object of Employee class emp1 = Employee("Zara", 2000)
 This would create second object of Employee class emp2 = Employee("Manni", 5000)
 Accessing Attributes
 You access the object's attributes using the dot operator with object. Class variable would be accessed
using class name as follows-
 emp1.displayEmployee() emp2.displayEmployee()
 print ("Total Employee %d" % Employee.empCount)
 (4) Instances as Arguments:
 Instance variables are always prefixed with the reserved word self. They are typically introduced and
initialized in a constructor method named init .
 In the following example, the variables self.name and self.grades are instance variables, whereas the
variable NUM_GRADES is a class variable:
Here “self” is a instance and “name” is a argument
The PVM automatically calls the constructor method when the programmer requests a new instance of the class, as follows:
s = Student('Mary')
The constructor method always expects at least one argument, self. When the method is called, the object being instantiated is
passed here and thus is bound to self throughout the code. Other arguments may be given to supply initial values for the
object’s data.
 Instances as return values:
 Built-in Class Attributes:
 Every Python class keeps the following built-in attributes and they can be accessed
 using dot operator like any other attribute −
 • dict : Dictionary containing the class's namespace.
 • doc : Class documentation string or none, if undefined.
 • name : Class name.
 • module : Module name in which the class is defined. This attribute is " main " in interactive mode.
 • bases : A possibly empty tuple containing the base classes, in the order of their occurrence in the base
class list.
 For the above class let us try to access all these attributes-
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
 Inheritance:
 Instead of starting from a scratch, you can create a class by deriving it from a pre- existing class by listing
the parent class in parentheses after the new class name.
 The child class inherits the attributes of its parent class, and you can use those attributes as if they were
defined In the child class. A child class can also override data members and methods from the parent.
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
 In a similar way, you can drive a class from multiple parent classes as follows-
 You can use issubclass() or isinstance() functions to check a relationship of two classes and instances.
 • The issubclass(sub, sup) boolean function returns True, if the given subclass sub is indeed a subclass of the
superclass sup.
 • The isinstance(obj, Class) boolean function returns True, if obj is an instance of class Class or is an
instance of a subclass of Class.
 Method Overriding:
 You can always override your parent class methods. One reason for overriding parent's methods is that you
may want special or different functionality in your subclass.
 Data Encapsulation:
 Simplifying the script by identifying the repeated code and placing it in a function. This is called
’encapsulation’.
 Encapsulation is the process of wrapping a piece of code in a function, allowing you to take advantage of all
the things functions are good for.
 Generalization means taking something specific, such as printing the multiples of 2, and making it more
general, such as printing the multiples of any integer. This function encapsulates the previous loop and
generalizes it to print multiples of n:
 With the argument 4, the output is:
 By now you can probably guess how to print a multiplication table—by calling print multiples repeatedly
with different arguments. In fact, we can use another loop:
 By now you can probably guess how to print a multiplication table—by calling print multiples repeatedly
with different arguments. In fact, we can use another loop:
 Data Hiding:
 An object's attributes may or may not be visible outside the class definition. You need to name attributes
with a double underscore prefix, and those attributes then will not be directly visible to outsiders.

PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
 Multithreaded Programming:
 (1)Thread Module:
 The newer threading module included with Python 2.4 provides much more
powerful, high-level support for threads than the thread module discussed in the
previous section.
 The threading module exposes all the methods of the thread module and provides
some additional methods:
 • threading.activeCount(): Returns the number of thread objects that are
active.
 • threading.currentThread(): Returns the number of thread objects in the
caller's thread control.
 • threading.enumerate(): Returns a list of all the thread objects that are
currently active.
 In addition to the methods, the threading module has the Thread class that implements
threading. The methods provided by the Thread class are as follows:
 • run(): The run() method is the entry point for a thread.
 • start(): The start() method starts a thread by calling the runmethod.
 • join([time]): The join() waits for threads to terminate.
 • isAlive(): The isAlive() method checks whether a thread is still executing.
 • getName(): The getName() method returns the name of a thread.
 • setName(): The setName() method sets the name of a thread.
 Creating a thread:
 To implement a new thread using the threading module, you have to do the following−
 • Define a new subclass of the Thread class.
 • Override the init (self [,args]) method to add additional arguments.
 • Then, override the run(self [,args]) method to implement what the thread should do when started.
 Once you have created the new Thread subclass, you can create an instance of it and then start a new
thread by invoking the start(), which in turn calls the run()method.
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
 Synchronizing threads:
 The threading module provided with Python includes a simple-to-implement locking mechanism that allows
you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock.
 The acquire(blocking) method of the new lock object is used to force the threads to run synchronously. The
optional blocking parameter enables you to control whether the thread waits to acquire the lock.
 If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and
with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be
released.
 The release() method of the new lock object is used to release the lock when it is no longer required.
 ------------------------------------------------------------------------------------------------------------
 multithreaded priority queue:
 The Queue module allows you to create a new queue object that can hold a specific number of items.
There are following methods to control the Queue −
 • get(): The get() removes and returns an item from the queue.
 • put(): The put adds item to a queue.
 • qsize() : The qsize() returns the number of items that are currently in the queue.
 • empty(): The empty( ) returns True if queue is empty; otherwise, False.
 • full(): the full() returns True if queue is full; otherwise, False.
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
 Modules:
 A module allows you to logically organize your Python code. Grouping related code into a module makes the
code easier to understand and use. A module is a Python object with arbitrarily named attributes that you
can bind and reference.
 Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A
module can also include runnable code.
 Example
 The Python code for a module named a name normally resides in a file namedaname.py. Here is an example
of a simple module, support.py
 1)Importing module:
 The import Statement
 You can use any Python source file as a module by executing an import statement in some other Python
source file. The import has the following syntax-
 When the interpreter encounters an import statement, it imports the module if the module is present in the
search path. A search path is a list of directories that the interpreter searches before importing a module.
For example, to import the module hello.py, you need to put the following command at the top of the
script
 Import module1[, module2[,... moduleN]
 When the interpreter encounters an import statement, it imports the module if the module is present in the
search path. A search path is a list of directories that the interpreter searches before importing a module.
For example, to import the module hello.py, you need to put the following command at the top of the
script-
 Import module support import support
 # Now you can call defined function that module as follows support.print_func("Zara")
 A module is loaded only once, regardless of the number of times it is imported.
 This prevents the module execution from happening repeatedly, if multiple imports occur.
 The from...import Statement
 Python's from statement lets you import specific attributes from a module into the current namespace. The
from...import has the following syntax-
 This provides an easy way to import all the items from a module into the current namespace; however, this
statement should be used sparingly.
 (2) Creating and exploringmodules: Creating modules
 Creating/Writing Python modules is very simple. To create a module of your own, simply create a new .py
file with the module name, and then import it using the Python file name (without the .py extension) using
the import command.
 Exploring built-in modules
 Two very important functions come in handy when exploring modules in Python - the dir and help functions.
 We can look for which functions are implemented in each module by using the dir function:
 Example:
 >>> import urllib
 >>> dir(urllib)
 [' builtins ', ' cached ', ' doc ', ' file ', ' loader ', ' name ', ' package ', ' path ', ' spec ', 'parse']
 Math module :
 This module is always available. It provides access to the mathematical functions defined by the C standard.
 These functions cannot be used with complex numbers; use the functions of the same name from the
cmath module if you require support for complex numbers. The distinction between functions which support
complex numbers and those which don’t is made since most users do not want to learn quite as much
mathematics as required to understand complex numbers.
 Receiving an exception instead of a complex result allows earlier detection of the unexpected complex
number used as a parameter, so that the programmer can determine how and why it was generated in the
first place.
 The following functions are provided by this module. Except when explicitly noted otherwise, all return
values are floats.
 (a) Number-theoretic and representation functions
 math.ceil(x)
 Return the ceiling of x as a float, the smallest integer value greater than or equal to x.
 math.copysign(x, y)
 Return x with the sign of y. On a platform that supports signed zeros, copysign(1.0, - 0.0) returns -1.0.
 New in version 2.6.
 math.fabs(x)
 Return the absolute value of x.
 math.factorial(x)
 Return x factorial. Raises ValueError if x is not integral or is negative.
 New in version 2.6.
 math.floor(x) Return the floor of x as a float, the largest integer value less than or equal to x.
 math.fmod(x, y)
 Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y
may not return the same result. The intent of the C standard is
 that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some
integer n such that the result has the same sign as x and magnitude less than abs(y).
 Python’s x % y returns a result with the sign of y instead, and may not be exactly computable
for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -
1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds
to the surprising 1e100. For this reason, function fmod() is generally preferred when working
with floats, while Python’s x % y is preferred when working with integers.
 math.frexp(x)
 Random module:
 This module implements pseudo-random number generators for various distributions. For integers, there is
uniform selection from a range. For sequences, there is uniform selection of a random element, a function
to generate a random permutation of a list in-
 Time Module:
 Time Module:
 Thank you stay connected :
 VISIT
 https://www.profajaypashankar.com
 For more study material and notes .
 VISIT
 https://www.youtube.com/channel/UCu4Bd22zM6RpvHWC9YHBh5Q?view_as=subscriber
 For more lectures .
 VISIT : FOR PRACTICAL MANUAL
 https://www.profajaypashankar.com/python-programming-practical-manual/
 Password:STUDYHARD

More Related Content

PPTX
Python advance
PPTX
Python OOPs
PPTX
Object Oriented Programming.pptx
PDF
Python unit 3 m.sc cs
PPTX
PPTX
Chapter 05 classes and objects
PDF
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
Python advance
Python OOPs
Object Oriented Programming.pptx
Python unit 3 m.sc cs
Chapter 05 classes and objects
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲

Similar to PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx (20)

PPT
Lesson on Python Classes by Matt Wufus 2003
PPTX
Class, object and inheritance in python
PPTX
IPP-M5-C1-Classes _ Objects python -S2.pptx
PDF
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PDF
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
PPTX
Introduction to Python , Overview
PPT
Python3
PPTX
python p.pptx
PPT
Spsl vi unit final
PPT
Spsl v unit - final
PDF
Anton Kasyanov, Introduction to Python, Lecture5
PDF
Unit 3-Classes ,Objects and Inheritance.pdf
PDF
Object_Oriented_Programming_Unit3.pdf
PPTX
About Python
PPTX
OOPS 46 slide Python concepts .pptx
PPT
Lecture topic - Python class lecture.ppt
PPT
Lecture on Python class -lecture123456.ppt
PPT
Python session 7 by Shan
PPTX
Object oriented programming with python
Lesson on Python Classes by Matt Wufus 2003
Class, object and inheritance in python
IPP-M5-C1-Classes _ Objects python -S2.pptx
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
Introduction to Python , Overview
Python3
python p.pptx
Spsl vi unit final
Spsl v unit - final
Anton Kasyanov, Introduction to Python, Lecture5
Unit 3-Classes ,Objects and Inheritance.pdf
Object_Oriented_Programming_Unit3.pdf
About Python
OOPS 46 slide Python concepts .pptx
Lecture topic - Python class lecture.ppt
Lecture on Python class -lecture123456.ppt
Python session 7 by Shan
Object oriented programming with python
Ad

Recently uploaded (20)

PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
Module 3: Health Systems Tutorial Slides S2 2025
PDF
Types of Literary Text: Poetry and Prose
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Insiders guide to clinical Medicine.pdf
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Sunset Boulevard Student Revision Booklet
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
English Language Teaching from Post-.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
High Ground Student Revision Booklet Preview
PPTX
How to Manage Loyalty Points in Odoo 18 Sales
PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PDF
Open folder Downloads.pdf yes yes ges yes
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
Cardiovascular Pharmacology for pharmacy students.pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Module 3: Health Systems Tutorial Slides S2 2025
Types of Literary Text: Poetry and Prose
Abdominal Access Techniques with Prof. Dr. R K Mishra
Insiders guide to clinical Medicine.pdf
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Sunset Boulevard Student Revision Booklet
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
English Language Teaching from Post-.pdf
O7-L3 Supply Chain Operations - ICLT Program
High Ground Student Revision Booklet Preview
How to Manage Loyalty Points in Odoo 18 Sales
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
Open folder Downloads.pdf yes yes ges yes
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
Renaissance Architecture: A Journey from Faith to Humanism
Ad

PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx

  • 1. PYTHON PROGRAMMING UNIT IV PROF.AJAY PASHANKAR ASSISTANT PROFESSOR DEPARTMENT OF CS & IT K.M.AGRAWAL COLLEGE KALYAN www.profajaypashankar.com
  • 2.  Regular Expressions :  Concept of regular expression :  A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expressions are widely used in UNIX world.  The module re provides full support for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression.  We would cover two important functions, which would be used to handle regular expressions. Nevertheless, a small thing first: There are various characters, which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with regular expressions, we would use Raw Strings as r'expression'.
  • 3.  2)Various types of regular expressions:  Basic patterns that match single chars  • a, X, 9, < -- ordinary characters just match themselves exactly.  • . (a period) -- matches any single character except newline 'n'  • w -- matches a "word" character: a letter or digit or underbar [a-zA-Z0- 9_].  • W -- matches any non-word character.  • b -- boundary between word and non-word  • s -- matches a single whitespace character -- space, newline, return, tab  • S -- matches any non-whitespace character.  • t, n, r -- tab, newline, return  • d -- decimal digit [0-9]  • ^ = matches start of the string  • $ = match the end of the string  • -- inhibit the "specialness" of a character.
  • 5.  Using match function.:  This function attempts to match RE pattern to string with optional flags. Here is the syntax for this function-  re.match(pattern, string, flags=0) The re.match function returns a match object on success, None on failure. We use group(num) or groups() function of match object to get matched expression.
  • 8.  Classes and Objects:  Python is an object-oriented programming language, which means that it provides features that support object-oriented programming (OOP).  Object-oriented programming has its roots in the 1960s, but it wasn’t until the mid 1990s that it became the main programming paradigm used in the creation of new software.  It was developed as a way to handle the rapidly increasing size and complexity of software systems, and to make it easier to modify these large and complex systems over time. Up to this point we have been writing programs using a procedural programming paradigm.  In procedural programming the focus is on writing functions or procedures which operate on data. In object-oriented programming the focus is on the creation of objects which contain both data and functionality together.
  • 9.  Overview of OOP (Object Oriented Programming):  a. Class: A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation.  b. Class variable: A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are.  c. Data member: A class variable or instance variable that holds data associated with a class and its objects.  d. Function overloading: The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved.  e. Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class.
  • 10.  f. Inheritance: The transfer of the characteristics of a class to other classes that are derived from it.  g. Instance: An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle.  h. Instantiation: The creation of an instance of a class.  i. Method : A special kind of function that is defined in a class definition.  j. Object: A unique instance of a data structure that is defined by its class. An object comprises both data members (class variables and instance variables) and methods.  k. Operator overloading: The assignment of more than one function to a particular operator. 
  • 11.  Class Definition:  The class statement creates a new class definition. The name of the class immediately follows the keyword class followed by a colon as follows-
  • 12.  The variable empCount is a class variable whose value is shared among all the instances of a in this class. This can be accessed as Employee.empCount from inside the class or outside the class.  • The first method init () is a special method, which is called class constructor or initialization method that Python calls when you create a new instance of this class.  • You declare other class methods like normal functions with the exception that the first argument to each method is self. Python adds the self argument to the list for you; you do not need to include it when you call the methods.
  • 13.  Creating Objects:  To create instances of a class, you call the class using class name and pass inwhatever arguments its init method accepts.  This would create first object of Employee class emp1 = Employee("Zara", 2000)  This would create second object of Employee class emp2 = Employee("Manni", 5000)  Accessing Attributes  You access the object's attributes using the dot operator with object. Class variable would be accessed using class name as follows-  emp1.displayEmployee() emp2.displayEmployee()  print ("Total Employee %d" % Employee.empCount)
  • 14.  (4) Instances as Arguments:  Instance variables are always prefixed with the reserved word self. They are typically introduced and initialized in a constructor method named init .  In the following example, the variables self.name and self.grades are instance variables, whereas the variable NUM_GRADES is a class variable: Here “self” is a instance and “name” is a argument The PVM automatically calls the constructor method when the programmer requests a new instance of the class, as follows: s = Student('Mary') The constructor method always expects at least one argument, self. When the method is called, the object being instantiated is passed here and thus is bound to self throughout the code. Other arguments may be given to supply initial values for the object’s data.
  • 15.  Instances as return values:
  • 16.  Built-in Class Attributes:  Every Python class keeps the following built-in attributes and they can be accessed  using dot operator like any other attribute −  • dict : Dictionary containing the class's namespace.  • doc : Class documentation string or none, if undefined.  • name : Class name.  • module : Module name in which the class is defined. This attribute is " main " in interactive mode.  • bases : A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.  For the above class let us try to access all these attributes-
  • 18.  Inheritance:  Instead of starting from a scratch, you can create a class by deriving it from a pre- existing class by listing the parent class in parentheses after the new class name.  The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined In the child class. A child class can also override data members and methods from the parent.
  • 20.  In a similar way, you can drive a class from multiple parent classes as follows-  You can use issubclass() or isinstance() functions to check a relationship of two classes and instances.  • The issubclass(sub, sup) boolean function returns True, if the given subclass sub is indeed a subclass of the superclass sup.  • The isinstance(obj, Class) boolean function returns True, if obj is an instance of class Class or is an instance of a subclass of Class.
  • 21.  Method Overriding:  You can always override your parent class methods. One reason for overriding parent's methods is that you may want special or different functionality in your subclass.
  • 22.  Data Encapsulation:  Simplifying the script by identifying the repeated code and placing it in a function. This is called ’encapsulation’.  Encapsulation is the process of wrapping a piece of code in a function, allowing you to take advantage of all the things functions are good for.  Generalization means taking something specific, such as printing the multiples of 2, and making it more general, such as printing the multiples of any integer. This function encapsulates the previous loop and generalizes it to print multiples of n:
  • 23.  With the argument 4, the output is:  By now you can probably guess how to print a multiplication table—by calling print multiples repeatedly with different arguments. In fact, we can use another loop:  By now you can probably guess how to print a multiplication table—by calling print multiples repeatedly with different arguments. In fact, we can use another loop:
  • 24.  Data Hiding:  An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then will not be directly visible to outsiders. 
  • 26.  Multithreaded Programming:  (1)Thread Module:  The newer threading module included with Python 2.4 provides much more powerful, high-level support for threads than the thread module discussed in the previous section.  The threading module exposes all the methods of the thread module and provides some additional methods:  • threading.activeCount(): Returns the number of thread objects that are active.  • threading.currentThread(): Returns the number of thread objects in the caller's thread control.  • threading.enumerate(): Returns a list of all the thread objects that are currently active.
  • 27.  In addition to the methods, the threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows:  • run(): The run() method is the entry point for a thread.  • start(): The start() method starts a thread by calling the runmethod.  • join([time]): The join() waits for threads to terminate.  • isAlive(): The isAlive() method checks whether a thread is still executing.  • getName(): The getName() method returns the name of a thread.  • setName(): The setName() method sets the name of a thread.
  • 28.  Creating a thread:  To implement a new thread using the threading module, you have to do the following−  • Define a new subclass of the Thread class.  • Override the init (self [,args]) method to add additional arguments.  • Then, override the run(self [,args]) method to implement what the thread should do when started.  Once you have created the new Thread subclass, you can create an instance of it and then start a new thread by invoking the start(), which in turn calls the run()method.
  • 30.  Synchronizing threads:  The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock.  The acquire(blocking) method of the new lock object is used to force the threads to run synchronously. The optional blocking parameter enables you to control whether the thread waits to acquire the lock.  If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released.  The release() method of the new lock object is used to release the lock when it is no longer required.  ------------------------------------------------------------------------------------------------------------  multithreaded priority queue:  The Queue module allows you to create a new queue object that can hold a specific number of items. There are following methods to control the Queue −  • get(): The get() removes and returns an item from the queue.  • put(): The put adds item to a queue.  • qsize() : The qsize() returns the number of items that are currently in the queue.  • empty(): The empty( ) returns True if queue is empty; otherwise, False.  • full(): the full() returns True if queue is full; otherwise, False.
  • 33.  Modules:  A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.  Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.  Example  The Python code for a module named a name normally resides in a file namedaname.py. Here is an example of a simple module, support.py
  • 34.  1)Importing module:  The import Statement  You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax-  When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module hello.py, you need to put the following command at the top of the script  Import module1[, module2[,... moduleN]  When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module. For example, to import the module hello.py, you need to put the following command at the top of the script-  Import module support import support  # Now you can call defined function that module as follows support.print_func("Zara")
  • 35.  A module is loaded only once, regardless of the number of times it is imported.  This prevents the module execution from happening repeatedly, if multiple imports occur.  The from...import Statement  Python's from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax-  This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.
  • 36.  (2) Creating and exploringmodules: Creating modules  Creating/Writing Python modules is very simple. To create a module of your own, simply create a new .py file with the module name, and then import it using the Python file name (without the .py extension) using the import command.  Exploring built-in modules  Two very important functions come in handy when exploring modules in Python - the dir and help functions.  We can look for which functions are implemented in each module by using the dir function:  Example:  >>> import urllib  >>> dir(urllib)  [' builtins ', ' cached ', ' doc ', ' file ', ' loader ', ' name ', ' package ', ' path ', ' spec ', 'parse']
  • 37.  Math module :  This module is always available. It provides access to the mathematical functions defined by the C standard.  These functions cannot be used with complex numbers; use the functions of the same name from the cmath module if you require support for complex numbers. The distinction between functions which support complex numbers and those which don’t is made since most users do not want to learn quite as much mathematics as required to understand complex numbers.  Receiving an exception instead of a complex result allows earlier detection of the unexpected complex number used as a parameter, so that the programmer can determine how and why it was generated in the first place.  The following functions are provided by this module. Except when explicitly noted otherwise, all return values are floats.  (a) Number-theoretic and representation functions  math.ceil(x)  Return the ceiling of x as a float, the smallest integer value greater than or equal to x.  math.copysign(x, y)  Return x with the sign of y. On a platform that supports signed zeros, copysign(1.0, - 0.0) returns -1.0.  New in version 2.6.  math.fabs(x)  Return the absolute value of x.  math.factorial(x)  Return x factorial. Raises ValueError if x is not integral or is negative.  New in version 2.6.  math.floor(x) Return the floor of x as a float, the largest integer value less than or equal to x.
  • 38.  math.fmod(x, y)  Return fmod(x, y), as defined by the platform C library. Note that the Python expression x % y may not return the same result. The intent of the C standard is  that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y).  Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s - 1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.  math.frexp(x)
  • 39.  Random module:  This module implements pseudo-random number generators for various distributions. For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-
  • 42.  Thank you stay connected :  VISIT  https://www.profajaypashankar.com  For more study material and notes .  VISIT  https://www.youtube.com/channel/UCu4Bd22zM6RpvHWC9YHBh5Q?view_as=subscriber  For more lectures .  VISIT : FOR PRACTICAL MANUAL  https://www.profajaypashankar.com/python-programming-practical-manual/  Password:STUDYHARD