Professional Documents
Culture Documents
by
C. RAJEEV
C. RAJEEV
Assistant Professor,
Assist. Prof.
Department of CSE,
Dept. of. CSE,
MRECW MRECW.
UNIT V
Python Packages, Python Libraries, Python Modules, Collection Module, Math Module, OS
Module, Random Module, Statistics Module, Sys Module, Date & Time Module, Loading the
Module in our Python Code, import Statement, from-import Statement, Renaming a Module,
Inheritance, Polymorphism, Data Abstraction, Encapsulation, Python Class and Objects, Creating
Classes in Python, Creating an Instance of the Class, Python Constructor, Creating the,
Class Functions, In-built Class Attributes, Python Inheritance, Python Multi-Level Inheritance,
Graphical User Interface (GUI) Programming, Python Tkinter, Tkinter Geometry, pack()
1. Python Packages:
Modular programming :
Modular programming refers to the process of breaking a large, unwieldy programming task
into separate, smaller, more manageable subtasks or modules. Individual modules can then be
cobbled together like building blocks to create a larger application.
Functions, modules and packages are all constructs in Python that promote code
modularization.
Python Package:
Packages are also known as directories. A package can contain many other
packages and modules. Python has packages for directories and modules for files.
As our application program grows larger in size with a lot of modules, we place similar
modules in one package and different modules in different packages. This makes a project
(program) easy to manage and conceptually clear.
Similarly, as a directory can contain subdirectories and files, a Python package can have
sub-packages and modules.
Each package should have a file called__init__.py The __init__.py can be empty but
should exist that makes the regular directory a Python package.
Using a Package
Once the package is installed, it is ready to use. Import the "camelcase" package into your project.
Example
Import and use "camelcase":
Program: capitalizes the first letter of each word in text
import camelcase
c = camelcase.CamelCase() Output: Hello
txt = "hello world” World
The PIP Package Manager will ask you to confirm that you want to remove the camelcase package:
Uninstalling camelcase-02.1:
Would remove:
c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase-0.2
py3.6.egg-info
c:\users\Your Name\appdata\local\programs\python\python36-32\lib\site-packages\camecase\*
Proceed (y/n)?
Press y and the package will be removed.
List Packages
Use the list command to list all the packages installed on your system:
Example
List installed packages:
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip list
Result:
Package Version
--------------------------------
camelcase 0.2
mysql-connector 2.1.6
pip 18.1
pymongo 3.6.1
setuptools 39.0.1
Features of PIP :
Pip is already installed for versions above Python 2.7.9 or Python 3 and above .
PIP can be installed through the system package manager or by invoking cURL,
a client-side data transfer tool.
Users not only install a package but also uninstall it very easily .
PIP also manages the list of packages along with its version numbers.
2. PYTHON MODULES
What are modules in Python?
If we need to reuse the code then we can define functions, but if we need to reuse
A python module can be defined as a python program file which contains a python code
including python functions, class, or variables.
for e.g.: example.py, is called a module and its module name would be example.
Modules provide reusability of code. Modules provides us the flexibility to organize the
code in a logical way.
To use the functionality of one module into another, we must have to import the
specific module.
Modules are three types:
1. Standard modules
2. User-defined modules
3. Third party modules
1.Standard modules:
These modules are already defined and kept in python software .so, when we install
python then automatically these standards modules will install in our machine.
Ex: math, calender, os, sys,..etc
2. User-defined modules
These modules are defined by user as per their requirement .so, here .py file contains
methods, variables, and classes.
3. Third party modules:
These modules are already defined by some other people and kept in internet . So
that, we can download and install in our machines by using PIP(pyhton package
installing)
PIP is a package management system used to install and manage software packages
written in python like..pymysql, cx_oracle
3. Loading the Module in our Python Code
We can import module in three ways:
1. import <module_name>
2. from <module_name> import <method_name>
3. from <module_name> import *
1. import <module_name>:
We can import all methods which is presented in that specified modules
Ex: import math
We can import all methods which are available in math module
2. from <module_name> import <method_name>:
This import statement will import a particular method from the module which is
specified in import statement.
Ex: from math import pi
We cannot use other methods which are available in that module.
But, we need to avoid this type of modules as they may cause name clashes in the
current python file
['','C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\Lib\\idlelib', 'C:\\Users\\
ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\ajee\\AppData\\
Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\ajee\\AppData\\Local\\Programs\\
Python\\Python37-32\\lib', 'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32',
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages', 'C:\\Users\\
ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\win32’,
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site- packages\\
win32\\lib',
‘C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\
Pythonwin‘]
In ubuntu python, module search path is like--
>>> import sys
>>> print '\n'.join(sys.path)
/usr/local/lib/python27.zip
/usr/local/lib/python2.7
/usr/local/lib/python2.7/plat-linux2
/usr/local/lib/python2.7/lib-tk
/usr/local/lib/python2.7/lib-old
/usr/local/lib/python2.7/lib-dynload
/usr/local/lib/python2.7/site-packages
It's possible to find out where a module is located after it has been imported, Using __file__
>>> import random # built_in module
>>> random.__file__
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\random.py‘
>>> import fact # user defined module
enter a number:5
Factorial of 5 is: 120
>>> fact.__file__
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32\\fact.py‘
But, file attribute is not present for C modules that are statically linked into the interpreter. Like
math, sys, time, itertools modules
Output
>>> import math
Traceback (most recent call last):
>>> math.file
File "<pyshell#28>", line 1, in <module>
math.file
AttributeError: module 'math' has no attribute 'file'
To know the C modules that are statically linked into the interpreter.
Execute the below command
>>> import sys
>>> print(sys.builtin_module_names)
Python provides a more efficient way of doing this. We can use the reload() function inside
the imp module to reload a module. We can do it in the following ways:
>>> import imp
>>> import my_module
This code got executed
>>> import my_module
>>> imp.reload(my_module)
This code got executed
<module 'my_module' from '.\\my_module.py'>
dir() built-in function
We can use the dir() function to find out names that are defined inside a module.
>>>import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin',
'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp',
'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf',
'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf',
'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
Here, we can see a sorted list of names . All other names that begin with an underscore are
default Python attributes associated with the module (not user-defined).
For example, the __name__ attribute contains the name of the module.
import math
>>> math.__name__
'math’
All the names defined in our current namespace can be found out using the dir() function
without any arguments.
In the following code, even though the 4th index was not initialized, the compiler still
returns a value, 0, when we try to access it.
In dicitionary, In collection,
print(dict['one']) nums['one'] = 1
print(dict['four']) nums['two'] = 2
Output nums['three'] = 3
1 print(nums['three'])
KeyError: 'four' print(nums['four'])
Output
3
2. Counter
Counter is a built-in data structure which is used to count the occurrence of each value
present in an array or list.
Ex
from collections import Counter
list = [1,2,3,4,1,2,6,7,3,8,1,2,2]
answer = Counter(list)
print(answer)
print(answer[2])
output
Counter({2: 4, 1: 3, 3: 2, 4: 1, 6: 1, 7: 1, 8: 1})
4
3. Deque
Deque is an optimal version of list used for inserting and removing items. It can add/remove
items from either start or the end of the list. In collections,
Ex In list,
from collections import deque
list = ["a","b","c"]
list = ["a","b","c"]
list.append("z")
deq = deque(list)
print(list)
print(deq)
list.appendleft("z")
deq.append("z")
print(list)
print(deq)
list.pop()
deq.appendleft("g")
print(list)
print(deq)
list.popleft()
deq.pop()
print(list) deque(['a', 'b', 'c'])
print(deq)
['a', 'b', 'c', 'z'] deque(['a', 'b', 'c', 'z'])
deq.popleft()
AttributeError: 'list' object has no
attribute‘appendleft' print(deq) deque(['g', 'a', 'b', 'c', 'z'])
['a', 'b', 'c'] deque(['g', 'a', 'b', 'c'])
AttributeError: 'list' object has no attribute 'popleft'
4. namedtuple( )
It returns a tuple with a named entry, which means there will be a name assigned to each
value in the tuple. It overcomes the problem of accessing the elements using the index
values. With namedtuple( ) it becomes easier to access these values, since you do not have
to remember the index values to get specific elements.
The namedtuple() function returns a tuple-like object with named fields. These field
attributes are accessible by lookup as well as by index.
syntax
collections.namedtuple(type_name, field-list)
Ex In the following code, an index is not required to print the name of a student rather passing
an attribute is sufficient for the required output.
from collections import namedtuple
Student = namedtuple('Student', 'fname, lname, age')
s1 = Student('Peter', 'James', '13')
output
print(s1.fname)
Peter
print(s1)
Student(fname='Peter', lname='James', age='13')
5. ChainMap
ChainMap combines a lot of dictionaries together and returns a list of dictionaries.
ChainMaps basically encapsulates a lot of dictionaries into one single unit with no
restriction on the number of dictionaries.
Ex
import collections
dictionary1 = { 'a' : 1, 'b' : 2 }
dictionary2 = { 'c' : 3, 'b' : 4 }
chain_Map = collections.ChainMap(dictionary1, dictionary2)
print(chain_Map.maps)
Output
[{'a': 1, 'b': 2}, {'c': 3, 'b': 4}]
6. OrderedDict
OrderedDict is a dictionary that ensures its order is maintained. For example, if the keys
are inserted in a specific order, then the order is maintained. Even if you change the value of
the key later, the position will remain the same.
Ex
In dicitonary,
statesAndCapitals = { 'Gujarat' : 'Gandhinagar', 'Maharashtra' : 'Mumbai', 'Rajasthan' :
'Jaipur', Bihar' : 'Patna’}
print('List Of given states:\n') Output:
print(state) Bihar
Maharashtra
Gujarat
In order to maintain the order of keys and values in a dictionary, use OrderedDict().
Program:
from collections import OrderedDict
statesAndCapitals = OrderedDict([ Output:
('Gujarat', 'Gandhinagar'), List Of given states:
('Maharashtra', 'Mumbai'), Gujarat
('Rajasthan', 'Jaipur'), Maharashtra
('Bihar', 'Patna') Rajasthan
]) Bihar
print('List Of given states:\n')
# Iterating over keys
for state in statesAndCapitals:
print(state)
8. Math module:
# importing built-in module math >>> math.ceil(10.9)
import math
11
# using square root(sqrt) function contained
# in math module >>> math.floor(10.9)
print math.sqrt(25)
10
# using pi function contained in math module >>> math.fabs(10)
print math.pi
10.0
# 2 radians = 114.59 degreees >>> math.fabs(-10)
print math.degrees(2)
10.0
# 60 degrees = 1.04 radians >>> math.fmod(10,2)
print math.radians(60)
0.0
# Sine of 2 radians >>> math.fsum([1,2,4])
print math.sin(2)
7.0
# Cosine of 0.5 radians >>> math.pow(2,3)
print math.cos(0.5)
8.0
>>> math.factorial(4)
# Tangent of 0.23 radians
24
print math.tan(0.23)
9. OS Module:
OS module provides functions for interacting with the operating system.
OS, comes under Python’s standard utility modules. This module provides a portable
way of using operating system dependent functionality.
1.os.name:
This function gives the name of the operating system dependent module(real module )
imported.
>>> import os
>>> os.name
'nt'
2. os.getcwd()
A directory or folder is a collection of files and sub directories.
We can get the present working directory using the getcwd() method.
This method returns the current working directory in the form of a string. We can also
use the getcwdb() method to get it as bytes object.
Ex:
>>> import os
>>> os.getcwd()
'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-32‘
>>> os.getcwdb()
b'C:\\Users\\ajee\\AppData\\Local\\Programs\\Python\\Python37-
32‘
The extra backslash implies escape sequence.
>>> print(os.getcwd())
C:\Users\ajee\AppData\Local\Programs\Python\Python37-32
3. os.chdir()
We can change the current working directory using the chdir() method.
Ex:
>>> os.chdir('C:\\Python3')
>>> os.getcwd()
'C:\\Python3'
>>> print(os.getcwd())
C:\Python3
4. os.listdir()
All files and sub directories inside a directory can be known using the listdir() method.
This method takes in a path and returns a list of sub directories and files in that path.
>>> import os
>>> print(os.getcwd())
C:\Users\ajee\AppData\Local\Programs\Python\Python37-32
>>> os.listdir()
['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo.txt', 'demo1', 'DLLs', 'Doc', 'dw.txt', 'include', 'Lib', 'libs',
If the full path is not specified, the new directory is created in the current working
directory.
>>> os.mkdir('test')
>>> os.listdir()
['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo.txt', 'demo1', 'DLLs', 'Doc', 'dw.txt', 'include', 'Lib',
The first argument is the old name and the new name must be supplies as the second
argument.
>>> os.rename('test','new_test')
>>> os.listdir()
['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo.txt', 'demo1', 'DLLs', 'Doc', 'dw.txt', 'include', 'Lib',
>>> os.listdir()
['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo.txt', 'demo1', 'DLLs‘, 'empty file‘, ‘non-
empty file’]
>>> os.remove('demo.txt')
['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo1', 'DLLs‘, 'empty file‘, ‘non-empty file’]
>>>os.rmdir('empty file')
However, note that rmdir() method can only remove empty directories.
In order to remove a non-empty directory we can use the rmtree() method and import
shutil module.
>>>os.rmdir('non-empty file')
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
os.rmdir('non-empty file')
OSError: [WinError 145] The directory is not empty: 'non-empty file‘
Ex
import sys
sys.stdout.write(‘hi I am standard files')
Output:
hi I am standard files
4. sys.stderr
This function of sys module is used to error message.
This function is standard file in python
Syntax:
sys.stderr.write()
Ex
import sys
sys.stderr.write(‘name a is not defined’)
Output:
name a is not defined
5. sys.version
To know the version of python
Ex
import sys
sys.version
output
3.7.10 (default, May 3 2021, 02:48:31) [GCC 7.5.0]
6. sys.exit
This method makes the Python interpretor exits the current flow of execution abruptly
Ex
import sys
print("python programming")
sys.exit(1)
print("datascience")
Output
python programming
7. sys.copyright
This function displays the copyright information on currently installed Python version.
Ex
import sys
sys.copyright
Output
Copyright (c) 2001-2021 Python Software Foundation.
All Rights Reserved.
Copyright (c) 2000 BeOpen.com.
All Rights Reserved.
Copyright (c) 1995-2001 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
8. sys.maxsize
This function returns the largest integer of a variable.
Ex
import sys
sys.maxsize
Output
9223372036854775807
8. sys.argv or Command line arguments :
Command line arguments in python:
Almost all programming language provide support for command line arguments. Then we
also have command line options to set some specific options for the program in python.
The command line arguments are those arguments must be given whenever we want to
give the input before the start of the script.
These arguments are given on the command line along with the program name in a text-
based environment like a unix- or dos-shell.
However, in an IDE or GUI environment, this would not be the case. Most IDES provide
a separate window with which to enter your "command-line arguments." These will be
passed into the program as if you started your application from the command line.
while on the other hand, raw_input() is used to get the input while the python program /
script is running.
There are many options to read python command line arguments. One of most common
1. Python sys.argv
Python sys.argv module
sys module provides access to any command-line arguments via sys.argv
Python sys module stores the command line arguments into a list, we can access it
using sys.argv.
This is very useful and simple way to read command line arguments as String.
The names "argc" and "argv" stand for "argument count" and "argument vector,“
The argv variable contains an array of strings consisting of each argument from the
command line while the argc variable contains the number of arguments entered.i.e., the
number of items in the sys.argv list.
4. seed() :- This function maps a particular random number with the seed
argument mentioned. All random numbers called after the seeded value returns the mapped
number >>> random.seed(7)
>>> random.seed(5) >>> print (random.random())
>>> print (random.random()) 0.32383276483316237
0.6229016948897019
5 uniform(a, b) :- This function is used to generate a floating point random number between the
numbers mentioned in its arguments. It takes two arguments, lower limit(included in generation)
and upper limit(not included in generation).
>>> import random
>>> random.uniform(5,10)
6.828444584562927
Example
import statistics
# declaring a simple data-set consisting of real valued positive integers.
dataset =[2, 4, 7, 7, 2, 2, 3, 6, 6, 8]
# Printing out the mode of given data-set
print("Calculated Mode % s" % (statistics.mode(dataset)))
Output:
Calculated Mode 2
4. stdev() function
The stdev() function is used to calculate the standard deviation on a given sample which is
available in the form of the list.
Example
import statistics
# creating a simple data - set
sample = [7, 8, 9, 10, 11]
# Prints standard deviation
print("Standard Deviation of sample is % s " % (statistics.stdev(sample)))
Output:
Standard Deviation of sample is 1.5811388300841898
4. variance() function
This function is used to calculate the standard deviation on a given sample which is
available in the form of the list.
Example
import statistics
datasets = [4, -5, 6, 6, 9, 4, 5, -2]
# Printing median of the
# random data-set
print("standard variance of data-set is :",statistics.variance(datasets))
Output
standard variance of data-set is : 21.125
14. datetime module
Python has a module named datetime to work with dates and times.
1. How to Get Current Date and Time:
import datetime
datetime_object = datetime.datetime.now()
print(datetime_object)
Output:
2020-06-15 12:25:54.193616
Here, we have imported datetime module using import datetime statement.
One of the classes defined in the datetime module is datetime class.
We then used now() method to create a datetime object containing the current local date and
time.
2. Get Current Date:
import datetime
date_object = datetime.date.today()
print(date_object)
Output:
2020-06-15
In this program, we have used today() method defined in the date class to get a date object
containing the current local date.
Output:
Current year: 2020
Current month: 6
Current day: 16
2. datetime.time class
A time object instantiated from the time class represents the local time.
Time object to represent time:
from datetime import time
# time(hour = 0, minute = 0, second = 0)
a = time()
print("a =", a)
# time(hour, minute and second)
b = time(11, 34, 56)
print("b =", b) Output:
The first three arguments year, month and day in the datetime() constructor are
mandatory.
4. Datetime.timedelta:
A timedelta object represents the difference between two dates or times.
from datetime import datetime, date
t1 = date(year = 2018, month = 7, day = 12)
t2 = date(year = 2017, month = 12, day = 23)
t3 = t1 - t2
print("t3 =", t3)
print("type of t3 =", type(t3))
Output:
t3 = 201 days, 0:00:00
type of t3 = <class 'datetime.timedelta'>
Output:
from datetime import datetime
date_string = 21 June, 2018
date_string = "21 June, 2018"
date_object = 2018-06-21 00:00:00
print("date_string =", date_string)
date_object = datetime.strptime(date_string, "%d %B, %Y")
print("date_object =", date_object)
Here , %d, %B and %Y format codes are used for day, month(full name) and year
respectively.
How to get current date and time in Python?
Python get today's date
from datetime import date
today = date.today()
print("Today's date:", today)
Output:
Today's date: 2020-06-15
Here, we imported the date class from the datetime module. Then, we used
the date.today() method to get the current local date.
By the way, date.today() returns a date object, which is assigned to the today variable in the
above program. Now, you can use the strftime() method to create a string representing date in
different formats.
Current date in different formats:
from datetime import date
today = date.today()
# dd/mm/YY
d1 = today.strftime("%d/%m/%Y")
print("d1 =", d1)
# Textual month, day and year
d2 = today.strftime("%B %d, %Y")
print("d2 =", d2)
# mm/dd/y
d3 = today.strftime("%m/%d/%y")
Output:
print("d3 =", d3)
d1 = 16/09/2019
# Month abbreviation, day and year
d2 = September 16, 2019
d4 = today.strftime("%b-%d-%Y")
d3 = 09/16/19
print("d4 =", d4)
d4 = Sep-16-2019
Get the current date and time:
If you need to get the current date and time, you can use datetime class of the datetime module.
from datetime import datetime
# datetime object containing current date and time
now = datetime.now()
print("now =", now)
# dd/mm/YY H:M:S
dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
print("date and time =", dt_string)
Output:
now = 2020-06-15 21:51:04.443980
date and time = 15/06/2020 21:51:04
Python time Module:
python has a module named time to handle time-related tasks. To use functions defined in the
module, we need to import the module first.
import time
Here are commonly used time-related functions:
1. Python time.time()
The time() function returns the number of seconds passed since epoch.
For Unix system, January 1, 1970, 00:00:00 at UTC is epoch (the point where time begins).
import time
seconds = time.time()
print("Seconds since epoch =", seconds)
Output:
Seconds since epoch = 1592241961.9925957
2. Python time.ctime()
The time.ctime() function takes seconds passed since epoch as an argument and returns a string
representing local time.
import time
# seconds passed since epoch
seconds = 1545925769.9618232
local_time = time.ctime(seconds)
print("Local time:", local_time)
Output:
Local time: Thu Dec 27 21:19:29 2018
Python time.sleep()
The sleep() function suspends (delays) execution of the current thread for the given number of
seconds.
import time
print("This is printed immediately.")
time.sleep(2.4)
print("This is printed after 2.4 seconds.")
Output:
This is printed immediately.
………
This is printed after 2.4 seconds.
15. Regular Expressions:
Introduction
The regular expressions can be defined as the sequence of characters which are
used to search for a pattern in a string.
It is extremely useful for extracting information from text such as code, files, log,
spreadsheets or even documents.
While using the regular expression the first thing is to recognize is that everything
is a character, and we are writing patterns to match a specific sequence of
characters also referred as string.
^a...s$
The above pattern defines a RegEx pattern.
The pattern is: any five letter string starting with a and ending with s.
Regex Functions
The following regex functions are used in the python.
1. re.match():
This method matches the regex pattern in the string .It returns true if a match is
found in the string otherwise it returns false.
import re
pattern = '^a...s$'
test_string = 'abyss'
result = re.match(pattern, test_string)
if result:
print("Search successful.")
else:
print("Search unsuccessful.")
Here, we used re.match() function to search pattern within the test_string. The
method returns a match object if the search is successful. If not, it
2. re.search()
The re.search() method takes two arguments: a pattern and a string. The method
looks for the first location where the RegEx pattern produces a match with the string.
If the search is successful, re.search() returns a match object; if not, it returns None.
Syntax:
match = re.search(pattern, str)
Ex:
import re
string = "Python is fun“
match = re.search(‘fun', string)
if match:
print("pattern found inside the string")
else:
print("pattern not found")
3. The findall() function
This method returns a list containing a list of all matches of a pattern within the
string.
It returns the patterns in the order they are found. If there are no matches, then an
empty list is returned.
Example
>>> import re
>>> str="How are you. How is everything"
>>> matches=re.findall("How",str)
>>> print(matches)
['How', 'How']
4. re.split(pattern, string, [maxsplit=0]):
This methods helps to split string by the occurrences of given pattern.
Ex:
import re
result=re.split('y','Analytics')
Result
Output:
['Anal', 'tics']
ex:
>>> result=re.split('i','Analytics information',maxsplit=3)
>>> result
['Analyt', 'cs ', 'nformat', 'on']
5. re.sub(pattern, repl, string):
It helps to search a pattern and replace with a new sub string. If the pattern is
not found, string is returned unchanged.
Ex;
import re
result=re.sub('India','the World','AV is largest Analytics community of India')
result
Output: 'AV is largest Analytics community of the World'
2. Special Symbols and Characters:
Forming a regular expression
A regular expression can be formed by using the mix of meta-characters, special
sequences, and sets.
1. Meta-Characters
Metacharacter is a character with the specified meaning.
EX:
import re
match=re.match('[abc]','a')
if match:
print("matched")
else:
print("not matched") import re
match=re.match('[^a-e]','a')
if match:
import re print("matched")
match=re.match('[a-e]','a') else:
if match: print("not matched")
print("matched")
else:
print("not matched")
Ex:
import re
match=re.match('..',‘a')
if match:
print("matched")
else:
print("not matched“)
Output: not matched
import re
match=re.match('..','ac')
if match:
print("matched")
else:
print("not matched")
Output: matched
Ex:
import re
match=re.match('^a','ba')
if match:
print("matched")
else:
print("not matched")
For example, a car can be an object. If we consider the car as an object then its properties
would be – its color, its model, its price, its brand, etc. And its behavior/function would be
acceleration, slowing down, gear change.
Another example- If we consider a dog as an object then its properties would be- his color, his
breed, his name, his weight, etc. And his behavior/function would be walking, barking, playing,
etc.
Object-Oriented programming is famous because it implements the real-world entities like
objects, hiding, inheritance, etc in programming. It makes visualization easier because it is close
to real-world scenarios.
16. Object-Oriented Programming (OOP) vs Procedure Oriented Programming
(POP)
The basic difference between OOP and procedural programming is-
One way to think about POP is the same way you make lemonade for example. The
procedure of making lemonade involves- first taking water according to the need, then
adding sugar to the water, then adding lemon juice to the mixture, and finally mixing the
whole solution. And your lemonade is ready to serve.
In a similar way, POP requires a certain procedure of steps. A procedural program
consists of functions. This means that in the POP approach the program is divided into
functions, which are specific to different tasks. These functions are arranged in a specific
sequence and the control of the program flows sequentially.
Whereas an OOP program consists of objects. The object-Oriented approach divides the
program into objects. And these objects are the entities that bundle up the properties and the
behavior of the real-world objects.
POP is suitable for small tasks only. Because as the length of the program increases, the
complexity of the code also increases. And it ends up becoming a web of functions. Also, it
becomes hard to debug. OOP solves this problem with the help of a clearer and less complex
structure. It allows code re-usability in the form of inheritance.
Another important thing is that in procedure-oriented programming all the functions have
access to all the data, which implies a lack of security. Suppose you want to secure the
credentials or any other critical information from the world. Then the procedural approach fails
to provide you that security. For this OOP helps you with one of its amazing functionality known
as Encapsulation, which allows us to hide data. Don’t worry I’ll cover this in detail in the latter
part of this article along with other concepts of Object-Oriented Programming. For now, just
understand that OOP enables security and POP does not.
Programming languages like C, Pascal and BASIC use the procedural approach whereas Java,
Python, JavaScript, PHP, Scala, and C++ are the main languages that provide the Object-oriented
approach.
17.Python OOPs concept
1. Class
2. Object
3. Method
4. Inheritance
5. Data Abstraction
6. Encapsulation
7. Polymorphism
1. Class :
class is a collection of objects. Unlike the primitive data structures, classes are data
structures that the user defines. They make the code more manageable.
How to create Class in Python:
Like function definitions begin with the keyword def, in Python, we define a class using
the keyword class.
The first string is called docstring and has a brief description about the class. Although
not mandatory, this is recommended.
Syntax
class class_name:
class body
We define a class with a keyword “class” following the class_name and semicolon. And we
consider everything you write under this after using indentation as its body.
Ex:
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
A class creates a new local namespace where all its attributes are defined.
Attributes may be data or functions..
class MyClass:
‘"This is my second class“’
a = 10
def func(self):
print('Hello‘)
print(MyClass.a)
print(MyClass.func)
print(MyClass.__doc__)
There are also special attributes in it that begins with double underscores (__). For example,
__doc__ gives us the docstring of that class.
2. Objects:
Python is an object oriented programming language.
Object is simply a collection of data (variables) and methods (functions) that act on those
We can think of class as a sketch (prototype) of a house. It contains all the details about
we can create many objects from a class. An object is also called an instance of a class
When we define a class only the description or a blueprint of the object is created. There
is no memory allocation until we create its object. The object or instance contains real data
or information.
Syntax
Ex
ob = MyClass()
This will create a new instance object named ob. We can access attributes of objects using
the object name prefix.
Ex:
class MyClass:
"This is my second class"
a = 10
ob = MyClass() # creating object of a class
print(ob.a)
# Output: 10
We can access attributes of objects using the object name prefix.
Attributes may be data or method. Method of an object are corresponding functions of that
class. Any function object that is a class attribute defines a method for objects of that class.
This means to say, since MyClass.func is a function object (attribute of class), ob.func will be
a method object.
3. Methods
Objects can also contain methods. Methods in objects are functions that belong to the object
Let us create a method in the Person class:
Ex: Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age): Output: Hello my name is John
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Note: The self parameter is a reference to the current instance of the class, and is used
to access variables that belong to the class.
The self Parameter
The self parameter is a reference to the current instance of the class, and is used to
access variables that belongs to the class.
It does not have to be named self , you can call it whatever you like, but it has to be the
first parameter of any function in the class:
Output:
John Doe
Mike Olsen
Add the __init__() Function
So far we have created a child class that inherits the properties and methods from its
parent.
We want to add the __init__() function to the child class (instead of the pass keyword).
Note: The __init__() function is called automatically every time the class is being used to
create a new object.
When you add the __init__() function, the child class will no longer inherit the parent's
__init__() function.
Note: The child's __init__() function overrides the inheritance of the parent's __init__()
To keep the inheritance of the parent's __init__() function, add a call to the parent's __init__()
function:
Example
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
Now we have successfully added the __init__() function, and kept the inheritance of the
parent class, and we are ready to add functionality in the __init__() function.
Example:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
x = Person("John", "Doe") Output:
John Doe
x.printname()
Mike
Olsen
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
x = Student("Mike", "Olsen“)
x.printname()
Use the super() Function
Python also has a super() function that will make the child class inherit all the methods
and properties from its parent:
Example
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
By using the super() function, we do not have to use the name of the parent element, it will
automatically inherit the methods and properties from its parent.
Add Properties:
Example: Add a property called graduationyear to the Student class:
class Student(Person):
def __init__(self, fname, lname):
super().__init__(fname, lname)
self.graduationyear = 2019
In the example below, the year 2019 should be a variable, and passed into the Student class
when creating student objects. To do so, add another parameter in the __init__() function:
Example
Add a year parameter, and pass the correct year when creating objects:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
x = Student("Mike", "Olsen", 2019)
x.printname()
print(x.graduationyear)
Add Methods
Example: Add a method called welcome to the Student class:
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
x=Student(“Kummari” ,“Spandana”,2024)
x.welcome()
Output:
Welcome Kummari Spandana to the class of 2024
If you add a method in the child class with the same name as a function in the parent class,
the inheritance of the parent method will be overridden.
Example:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
Output:
def __init__(self, fname, lname, year):
Welcome Mike Olsen to the class of 2019
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
x = Student("Mike", "Olsen", 2019)
x.welcome()
Two built-in functions isinstance() and issubclass() are used to check inheritances.
Function isinstance() returns True if the object is an instance of the class or other classes
derived from it. Each and every class in Python inherits from the base class, object.
Example: a=issubclass(Student,Person)
b=isinstance(x,Person) print(a)
print(b) f=issubclass(Person,Student)
c=isinstance(x,Student) print(f)
print(c)
d=isinstance(x,object)
print(d) Output: Output:
True True
e=isinstance(x,int) True False
print(e) Tru
False
Multiple Inheritance in Python
In Python., like C++, a class can be derived from more than one base classes. This is
called multiple inheritance.
In multiple inheritance, the features of all the base classes are inherited into the derived
class.
The syntax for multiple inheritance is similar to single inheritance.
Example
class Base1:
pass
class Base2:
pass
class MultiDerived(Base1, Base2):
pass
1. Data abstraction:
It refers to the act of representing essential features without including the background
details and explanations. i.e., Abstraction is the process of hiding the real
implementation of an application from the user and emphasizing only on how to use the
application.
Consider the example of a switchboard, you can only press certain switches according
to your requirement. What is happening inside, how it is happening, you need not
know.
Syntax
from abc import ABC
Class ClassName(ABC):
pass
An abstract class is created by importing a class named 'ABC' from the 'abc' module and
inheriting the 'ABC' class.
abstract methods should not contain any implementation. So, we can define abstract methods
using the 'pass' statement'
Example
from abc import ABC
class Shape(ABC): #abstract class
def calculate_area(self): #abstract method
pass
class Rectangle(Shape):
length = 5
breadth = 3
def calculate_area(self):
return self.length * self.breadth
class Circle(Shape):
radius = 4
def calculate_area(self):
return 3.14 * self.radius * self.radius
rec = Rectangle() #object created for the class 'Rectangle'
cir = Circle() #object created for the class 'Circle'
print("Area of a rectangle:", rec.calculate_area()) #call to 'calculate_area' method defined inside
the class 'Rectangle'
print("Area of a circle:", cir.calculate_area()) #call to 'calculate_area' method defined inside the
class 'Circle'.
Output:
Area of a rectangle: 15
Area of a circle: 50.24
encapsulation focuses upon the implementation that gives rise to this behaviour.
In Python, Encapsulation can be achieved by declaring the data members of a class either as
private or protected.
In Python, 'Private' and 'Protected' are called Access Modifiers, as they modify the access of
variables or methods defined in a class.
The access modifiers supported are:
1. Private:
A private variable can only be accessed by a method that is of the same class and not
outside of the class. These variables start with __ (private members are preceded by two
underscores).
For Example:
__engineno, __modelname
A private method can be called by a method of the same class. These methods start
with __.
For Example:
def __setmodelname()
In the below example, 'length' and 'breadth' are the two private variables declared and can
be accessed within the class 'Rectangle‘.
class Rectangle:
__length = 0 #private variable
__breadth = 0 #private variable
def __init__(self): #constructor
self. __length = 5
self.__breadth = 3 #printing values of the private variable within the class
print(self.__length)
print(self.__breadth)
rec = Rectangle() #object created for the class 'Rectangle'
#printing values of the private variable outside the class using the object created for the
class 'Rectangle'
print(rec.__length)
print(rec.__breadth)
output
5
3
AttributeError: 'Rectangle' object has no attribute ‘__length'
Since we have accessed private variables in the main() method, i.e., outside the class
'Rectangle', we got an error.
Hence in the above program, Encapsulation is achieved using the private variables 'length' and
'breadth'.
2. protected :
In Python, Protected members can be accessed within the class in which they are defined
and also within the derived classes.
protected members are preceded by a single underscore. In the below example, 'length'
and 'breadth' are the two protected variables defined inside the class 'Shape'.
When we try to access protected variables in the derived class, we got output. But, in the
main() method, we got an error.
Hence in the above example, Encapsulation is achieved using the protected variables 'length'
and 'breadth'.
3. Public:
A public variable can be accessed from anywhere.
A public method can be called from anywhere.
There is no specific word or character to represent the public access modifier. Anything
that does not have a __ is a public variable or method.
Ex:
class MyClass:
num = 10
def add(self, a):
sum = self.num + a
print(sum)
Output:
ob = MyClass()
30
ob.add(20)
10
print(ob.num)
7. Polymorphism
polymorphism refers to the ability of a real-time object to represent itself in many forms.
For example. When you are at college, you act as a student. When are at your home, you
act like a child. You are a single person, but you represent yourself differently in different
places.
Polymorphism is used in Python programs when you have commonly named methods in
two or more classes or subclasses.
It allows these methods to use objects of different types at different times. So, it provides
flexibility, using which a code can be extended and easily maintained over time.
Polymorphism In Built-In Method
In the below-given example, the built-in method 'len' processes two different objects, one
being a list & another a string.
#printing length of two different objects
print(len([2, 4, 6, 8, 9]))
print(len("FACE Prep"))
Output:
5
9
Here, the method 'len' prints the length of two different objects. In the first print statement, it
prints the length of a list object and in the second, it prints the length of a string object. So,
polymorphism is achieved using the built-in method 'len'.
Polymorphism In User-Defined Method
In the below diagram, 'calculate_area' is the user-defined method created with different
operations in both the classes 'Rectangle' and 'Circle'.
class Rectangle:
length = 5
breadth = 3
output
def calculate_area(self):
Area of a rectangle: 15
return self.length * self.breadth
Area of a circle: 50.24
class Circle:
radius = 4
def calculate_area(self):
return 3.14 * self.radius * self.radius
rec = Rectangle() #object created for the class 'Rectangle'
cir = Circle() #object created for the class 'Circle'
print("Area of a rectangle:", rec.calculate_area())
#call to 'calculate_area' method defined
inside the class 'Rectangle'
print("Area of a circle:", cir.calculate_area())
Here,
#call to polymorphism is achieved
'calculate_area' using the method 'calculate_area' that works differently in
method defined
different classes.
Polymorphism With Inheritance
In Python, polymorphism can be combined with Inheritance, i.e., polymorphism can also
be achieved in inherited classes.
Polymorphism allows us to define a child class method with the same name as that of a
parent class method.
In the example, 'Car' is the parent class and 'RaceCar' is the child class. A method named
'drive' is defined in both classes with different operations. So, polymorphism is achieved
using the method 'drive'.
program
class Car: #parent class
def drive(self): #parent class method
print("I can drive at a speed of 60km/hr")
class RaceCar(Car): #child class
def drive(self):
#child class method with the same name as that of the parent class
print("I can drive at a speed of 40km/hr")
#main() method
maruti1 = Car()
maruti2 = RaceCar()
maruti1.drive() #accessing the parent class method
maruti2.drive() #accessing the child class method
Output
I can drive at a speed of 60km/hr
I can drive at a speed of 40km/hr
Constructors in Python:
Constructors in Python are special methods that are defined inside a class.They are
invoked when an object is created for the class.
They also verify whether there are enough variables and methods available for an object
to perform a task defined in the class.
Syntax of constructor declaration :
Similar to Functions, a constructor is defined with the keyword 'def' followed by a constructor
def __init__(self):
# body of the constructor
A constructor always has the name 'init' and the name is prefixed, suffixed with a double
underscore(__). The first parameter of the constructor must be 'self'. This parameter is used
to store the object passed from the main() method.
In Python the __init__() method is called the constructor and is always called when an
object is created.
Types of constructors :
In Python, we have two types of constructors.
1) Default constructor
2) Parameterized constructor
1.default constructor :
The default constructor does not have any parameters other than 'self'. It will not accept any
arguments other than the object created for the class in which it is defined.
class Employee:
age = 0 #class variable
def __init__(self): # default constructor used to initialize 'age' with the value 22
self.age = 22
#main() method
John = Employee()
#creating object (John) for the class 'Employee'. Once the object is created, the Python inte
rpreter calls the default constructor
print(John.age) # printing the value stored in the variable 'age' using the object 'John‘
Output
22
If the user did not define a constructor inside a class, then the Python interpreter implicitly
defines a default constructor that does not do any operations.
We can pass arguments while creating an object and those arguments get stored in a
parameterized constructor.
Here, the values 22 and 20000 are passed as the arguments during the object creation to the
parameterized constructor defined inside the class 'Employee'.
These values get stored in the parameters 'age' and 'salary'. Later, both the values get assigned
to the variables 'age1' and 'salary1'.
We can also create another object for the same class and pass the arguments.
class Employee:
def __init__(self, age, salary):
output
self.age1 = age
John age: 22
self.salary1 = salary
John salary: 20000
#main() method
Alex age: 30
John = Employee(22, 20000)
Alex salary: 27000
Alex = Employee(30, 27000)
print("John age:", John.age1)
print("John salary:", John.salary1)
print("Alex age:", Alex.age1)
print("Alex salary:", Alex.salary1)
2. parameterized constructor :
constructor with parameters is known as parameterized constructor. The parameterized
constructor take its first argument as a reference to the instance being constructed known
as self and the rest of the arguments are provided by the programmer.
This constructor accepts and stores arguments passed from the main() method during
object creation
Ex
class Employee:
def __init__(self, age, salary):
self.age1 = age
self.salary1 = salary
#main() method
John = Employee(22, 20000) #passing arguments to the parameterized constructor
Output
print(John.age1)
22
print(John.salary1)
20000
Example of parameterized constructor :
class Addition:
def __init__(self, f, s): # parameterized constructor
self.first = f
self.second = s
def display(self):
print("First number = " + str(self.first))
print("Second number = " + str(self.second))
print("Addition of two numbers = " + str(self.answer))
def calculate(self):
self.answer = self.first + self.second
obj = Addition(1000, 2000) # creating object of the class
obj.calculate() # perform Addition Output :
obj.display() # display result
First number = 1000
Second number = 2000
Addition of two numbers = 300
Python - Built-in Class functions
Python - Built-in Class Attributes
We can access the built-in class attributes using the . operator.
Following are the built-in class attributes.
1. __doc__ class attribute
In the following Python program we are creating Awesome class with documentation
Program
class Awesome: # class
'This is a sample class called Awesome.'
def __init__(self):
print("Hello from __init__ method.") # class built-in attribute
print(Awesome.__doc__)
Output
This is a sample class called Awesome.
2. __name__ class attribute
In the following example we are printing the name of the class
Program
class Awesome:
'This is a sample class called Awesome.'
def __init__(self):
print("Hello from __init__ method.")
# class built-in attribute
print(Awesome.__name__)
Output
Awesome
3. _module__ class attribute
In the following example we are printing the module of the class
Program
class Awesome:
def __init__(self):
print("Hello from __init__ method.")
# class built-in attribute
print(Awesome.__module__)
Output
__main__
4. __bases__ class attribute
In the following example we are printing the bases of the class.
program
class Awesome:
def __init__(self):
print("Hello from __init__ method.")
# class built-in attribute
print(Awesome.__bases__)
Output
(<class 'object'>,)
5. __dict__ class attribute
In the following example we are printing the dict of the class.
Program
class Awesome:
def __init__(self):
print("Hello from __init__ method.")
# class built-in attribute
print(Awesome.__dict__)
Output
{'__module__': '__main__', '__init__': <function Awesome.__init__ at 0x7f16e62c27a0>,
'__dict__': <attribute '__dict__' of 'Awesome' objects>, '__weakref__': <attribute '__weakref__'
of 'Awesome' objects>, '__doc__': None}
Method overriding:
Overriding is the property of a class to change the implementation of a method provided
by one of its base classes.
The method overriding means creating two methods with the same name but differ in
the programming logic.
The concept of Method overriding allows us to change or override the Parent Class
function in the Child Class.
In python, inheritance involves a relationship between parent and child classes.
Whenever both the classes contain methods with the same name and arguments or
parameters it is certain that one of the methods will override the other method during
execution. The method that will be executed depends on the object.
If the child class object calls the method, the child class method will override the parent class
method. Otherwise, if the parent class object calls the method, the parent class method will be
executed.
Example
class Animal():
def sound(self, a): output
print("This is parent class") Dogs bark
class Dogs(Animal):
def sound(self):
print("Dogs bark")
d1 = Dogs()
d1.sound()
In the above example, the class Dogs and its parent class Animal have methods with the same
name sound. When the object d of the class Dogs calls this method, then the method of the child
class Dogs gets called, not that of the parent class. Thus, the method of the child class overrides
the method of the parent class when called by an object of the child class. This is called method