Python Mod 3
Python Mod 3
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'.
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.
Using match function: This function attempts to match RE pattern to string with optional flags.
Syntax:
re.match(pattern, string, flags=0)
Parameter Description
pattern This is the regular expression to be matched.
string This is the string, which would be searched to match the pattern at the beginning of string.
flags You can specify different flags using bitwise OR (I). These are modifiers, which are listed in
the table below.
Flag Meaning
Sakshi Jain 45208210753 F029
ASCII, A Makes several escapes like \w, \b, \s and \d match only on ASCII
characters with the respective property.
DOTALL, S Make, match any character, including newlines
IGNORECASE, I Do case-insensitive matches
LOCALE, L Do a locale-aware match
MULTILINE, M Multi-line matching, affecting ^ and $
VERBOSE, X (for 'extended') Enable verbose REs, which can be organized more cleanly and
understandably
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.
Example:
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?).*, line, re.Mre.I) if matchObj:
print ("matchObj.group(): ", matchObj.group())
print ("matchObj.group(1) : ", matchObj.group(1)) print ("matchObj.group(2): ", matchObj.group(2)) else:
print ("No match!!")
Output:
matchObj.group(): Cats are smarter than dogs
matchObj.group(1) : Cats
matchObj.group(2): smarter
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:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary): # Fixed: added an underscore
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name: ", self.name, ", Salary: ", self.salary)
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.
Sakshi Jain 45208210753 F029
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-
o emp1.displayEmployee()
o emp2.displayEmployee()
o print ("Total Employee %d" % Employee.empCount)
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:
Example:
class Student:
NUM_GRADES = 5
def __init__(self, name):
self.name = name
self.grades = []
for i in range(Student.NUM_GRADES):
self.grades.append(0)
For the above class let us try to access all these attributes:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Sakshi Jain 45208210753 F029
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name:", self.name, ", Salary:", self.salary)
emp1 = Employee("Zara", 2000)
emp2 = Employee("Manni", 5000)
print("Employee.__doc__:", Employee.__doc__)
print("Employee.__name__:", Employee.__name__)
print("Employee.__module__:", Employee.__module__)
print("Employee.__bases__:", Employee.__bases__)
print("Employee.__dict__:", Employee.__dict__)
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.
Example:
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name:", self.name, ", Salary:", self.salary)
emp1 = Employee("Zara", 2000)
emp2 = Employee("Manni", 5000)
print("Employee.__doc__:", Employee.__doc__)
print("Employee.__name__:", Employee.__name__)
Sakshi Jain 45208210753 F029
print("Employee.__module__:", Employee.__module__)
print("Employee.__bases__:", Employee.__bases__)
print("Employee.__dict__:", Employee.__dict__)
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.
Example:
class Parent: # Define parent class
def myMethod(self):
print('Calling parent method') Output: Calling child method
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:
def print_multiples(n):
i=1
while i <= 6:
print (n * i, "\t",)
i += 1
print()
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.
Sakshi Jain 45208210753 F029
Multithreaded Programming
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:
o threading.activeCount(): Returns the number of thread objects that are active.
o threading.currentThread(): Returns the number of thread objects in the caller's thread control.
o 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.
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.
Sakshi Jain 45208210753 F029
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.
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.
1) Importing module
a. The import Statement:
You can use any Python source file as a module by executing an import statement in some other Python
source file.
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:
Syntax: 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.
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.
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: