You are on page 1of 183

PYTHON PROGRAMMING

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,

Regular Expressions, Command Line Arguments, Object Oriented Programming (OOPs),

Object-oriented vs Procedure-oriented Programming languages, Object, Class, Method,

Inheritance, Polymorphism, Data Abstraction, Encapsulation, Python Class and Objects, Creating

Classes in Python, Creating an Instance of the Class, Python Constructor, Creating the,

Constructor in Python, Parameterized Constructor, Non-Parameterized Constructor, In- built

Class Functions, In-built Class Attributes, Python Inheritance, Python Multi-Level Inheritance,

Python Multiple Inheritance, Method Overriding, Data Abstraction in Python,

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.

There are several advantages to modularizing code in a large application :


1. Simplicity
2. Maintainability
3. Reusability

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.

 If the file __init__.py is present in a package, it specifies the package and


its modules can be imported.
Here is an example. Suppose we are developing a game. One possible organization of packages
and modules could be as shown in the figure below.

Importing module from a package


We can import modules from packages using the dot (.) operator.
For example, if we want to import the start module.
import Game.Level.start
Now, if this module contains a function named select_difficulty(), we must use the full name
to reference it.
Game.Level.start.select_difficulty(2)
if this construct seems lengthy, we can import the module without the package prefix as
follows:
from Game.Level import start
We can now call the function simply as follows:
start.select_difficulty(2)
Another way of importing just the required function (or class or variable) from a module
within a package would be as follows:
from Game.Level.start import select_difficulty
Now we can directly call this function.
select_difficulty(2)
Although easier, this method is not recommended. Using the full namespace avoids
confusion and prevents two same identifier names from colliding.
While importing packages, Python looks in the list of directories defined in sys.path, similar as
We can see help function in python to get the list of modules installed.
>>>help("modules")
Python PIP (Preferred Installer Program ):
"Pip Installs Packages" or "Pip Installs Python“.
PIP is a package manager for Python packages, or modules.
PIP - is a package management system that helps in installing Python packages and managing
them. Many packages exist in the default source.
What is a Package?
A package contains all the files you need for a module. Modules are Python code libraries you
can include in your project.
Check if PIP is Installed
Navigate your command line to the location of Python's script directory, and type thefollowing:
Example
Check PIP version:
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip –version
Install PIP
If you do not have PIP installed, you can download and install it from this page:
https://pypi.org/project/pip/
Download a Package
Downloading a package is very easy.
Open the command line interface and tell PIP to download the package you want.
Navigate your command line to the location of Python's script directory, and type the following:
Example
Download a package named "camelcase":
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip install camelcase

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

print(c.hump(txt)) #This method capitalizes the first letter of each word.


Find Packages
Find more packages at https://pypi.org/.
Remove a Package
Use the uninstall command to remove a package:
Example
Uninstall the package named "camelcase“:
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip uninstall camelcase

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 stands for "Preferred Installer Program".

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.

PIP is used because it is easy to use it through the command-line interface.

Using PIP, installing python packages is just a single command.

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

number of functions then we have to go for modules

Modules refer to a file containing Python statements and definitions.

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

3. from <module_name> import * :


This import statement will import all methods from the specified module and also we
can import all names(definitions) from a module
Ex: from math import *
4. Renaming a Module
We can import a module by renaming it as follows.
>>> import math
>>> math.pi
3.141592653589793

>>> import math as m


>>> m.pi
3.141592653589793
5. Python Module Search Path
While importing a module, Python looks at several places. Interpreter first looks for a
built-in module.
Then(if built-in module not found), Python looks into a list of directories defined in
sys.path. The search is in this order.
1. The directory from which the input script was run or the current directory if the
interpreter is being run interactively.

2. The list of directories contained in the PYTHONPATH environment variable, if


it is set. (The format for PYTHONPATH is OS-dependent but should mimic
the PATH environment variable.)

3. An installation-dependent list of directories configured at the time Python is


installed
The resulting search path is accessible in the Python variable sys.path, which is obtained from a
module named sys:
>>> import sys
>>> sys.path

['','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)

('_abc', '_ast', '_bisect', '_blake2', '_codecs', '_codecs_cn', '_codecs_hk', '_codecs_iso2022',


'_codecs_jp', '_codecs_kr', '_codecs_tw', '_collections', '_contextvars', '_csv', '_datetime',
'_functools', '_heapq', '_imp', '_io', '_json', '_locale', '_lsprof', '_md5', '_multibytecodec', '_opcode',
'_operator', '_pickle', '_random', '_sha1', '_sha256', '_sha3', '_sha512', '_signal', '_sre', '_stat',
'_string', '_struct', '_symtable', '_thread', '_tracemalloc', '_warnings', '_weakref', '_winapi', 'array',
'atexit', 'audioop', 'binascii', 'builtins', 'cmath', 'errno', 'faulthandler', 'gc', 'itertools', 'marshal',
'math', 'mmap', 'msvcrt', 'nt', 'parser', 'sys', 'time', 'winreg', 'xxsubtype', 'zipimport', 'zlib')
6. Reloading a module
The Python interpreter imports a module only once during a session. This makes things
more efficient.
Here is an example to show how this works.
Suppose we have the following code in a module named my_module.
my_module.py
# This module shows the effect of
# multiple imports and reload
print("This code got executed")

Now we see the effect of multiple imports.


>>> import my_module
This code got executed
>>> import my_module
>>> import my_module
We can see that our code got executed only once. This goes to say that our module was
imported only once.
Now if our module changed during the course of the program, we would have to reload it.
One way to do this is to restart the interpreter. But this does not help much.

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.

>>> import math


>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'math']
7. Python Collection Module
The Python collection module is defined as a container that is used to store collections of
data, for example - list, dict, set, and tuple, etc.
Collections module provides us with improved functionalities and highly optimized
alternatives to inbuilt Python containers like List, Tuple, Dictionary, etc.,
Python collection module was first introduced in its 2.4 release.
There are 6 most commonly used data structures in the collections modules.
1. Defaultdict:
Defaultdict is exactly like a dictionary in python. The only difference is that it does not
give an exception/key error when you try to access the non-existent key.

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,

dict={'one': 1, 'two': 2, 'three': 3} from collections import defaultdict

print(dict) nums = defaultdict(int)

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:

# Iterating over keys List Of given states:

for state in statesAndCapitals: Rajasthan

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.

If no path is specified, it returns from the current working directory.

>>> 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',

'LICENSE.txt', 'new1.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python37.dll', 'pythonw.exe‘]


5. os.mkdir( )
We can make a new directory using the mkdir() method. This method takes in the path

of the new directory.

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',

'libs', 'LICENSE.txt', 'new1.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python37.dll',

'pythonw.exe', 'tcl', 'test‘]


6. os.rename( )
The rename() method can rename a directory or a file.

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',

'libs', 'LICENSE.txt', 'new1.txt', 'NEWS.txt', 'new_test‘]


7. Removing Directory or File

A file can be removed (deleted) using the remove() method.

Similarly, the rmdir() method removes an empty directory.

>>> 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')

['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo1', 'DLLs‘, ‘non-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‘

>>> import shutil


>>> shutil.rmtree('non-empty file')
>>> os.listdir()
['a.txt', 'ab.txt', 'data.txt', 'demo', 'demo1', 'DLLs‘]
10.Sys module:
python sys module provides allows us to operate on underlying interpreter(i.e., system
and environment-specific variables ), irrespective of it being a Windows Platform, Macintosh
or Linux.
Python sys module also used to read the PATH variable and the list of command-line
parameters passed to the Python script.
Functions in sys module
1. sys.modules.keys()
This function gives the names of the existing python modules current shell has
imported
Ex
import sys
sys.modules.keys()
Output
dict_keys(['sys', 'builtins', '_frozen_importlib', '_imp', '_thread',
'_warnings‘………'zmq.utils.garbage'])
2. sys.path
This function displays the PATH of the current system or environment.
>>> import sys
>>> sys.path
['','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‘]
3. sys.stdin
This function of sys module is used to accept input for a user-input-prompt program.
This function is standard file in python
Syntax:
sys.stdin.readline()
Ex
import sys
print('Enter your name: ')
c = sys.stdin.readline()
print('Your name is:', c)
Output:
Enter your name: rajeev
Your name is: rajeev
4. sys.stdout
This function of sys module is used to print message.
This function is standard file in python
Syntax:
sys.stdout.write()

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:

Till now in python , we have taken input using raw_input() or input().

There is another method that uses command line arguments.

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

method to read python command line arguments is:

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.

In list, each element represents a single argument.


The first one -- sys.argv[0] -- is the name of the Python script or program name.
The other list elements -- are the command line arguments 2 to n.
sys.argv is the list of command-line arguments
len(sys.argv) is the number of command-line arguments
Ex:
# file save as cmd.py
import sys
print("you entered", len(sys.argv), "arguments...")
print(len(sys.argv),'agruments input from command line are:')
for x in sys.argv:
print(x)
Open cmd prompt and execute below cmd where your python software is installed.
>>C:\Users\ajee\AppData\Local\Programs\Python\Python37-32>python cmd.py 2 3 4 5
you entered 5 arguments...
5 agruments input from command line are:
cmd.py
2
3
4
5
Python program to find sum of two numbers using command line arguments
Program:
import sys
print("you entered", len(sys.argv), "arguments...")
print("they were:", str(sys.argv))
a = int(sys.argv[1])
b = int(sys.argv[2])
sum = a+b
print("sum of",sys.argv[1],"and",sys.argv[2],"is",sum)
Output :
C:\Users\ajee\AppData\Local\Programs\Python\Python37-32>python cmd.py 20 30
you entered 3 arguments...
they were: ['cmd.py', '20', '30']
sum of 20 and 30 is 50
11. Random module
Python defines a set of functions that are used to generate or manipulate random numbers.
This particular type of functions are used in a lot of games, lotteries or any application
requiring random number generation
Randon Number Operations :
1. choice() :- This function is used to generate 1 random number from a container.
2. randrange(beg, end, step) :- This function is also used to generate random number but within
a range specified in its arguments. This function takes 3 arguments, beginning number (included
in generation), last number (excluded in generation) and step ( to skip numbers in range while
selecting).
Ex:
>>> import random
>>> print(random.choice([1,2,4,5]))
5
>>> print(random.randrange(20,50,3))
23
3. random() :- This number is used to generate a float random number less than 1 and greater
or equal to 0.
>>> print (random.random())
0.17656383747256632

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

6. randint(): generate random integer between 0 and 5


Ex:
import random
# printing random integer between 0 and 5
print (random.randint(0, 5) )
12. Platform module
# to know your operting system
>>> import platform
>>> platform.system()
'Windows'
13. Statistics Module:
The statistics module provides functions to mathematical statistics of numeric data. The
following popular statistical functions are defined in this module.
1. mean() :
The mean() method calculates the arithmetic mean of the numbers in a list
Ex :
import statistics
# list of positive integer numbers
datasets = [5, 2, 7, 4, 2, 6, 8]
x = statistics.mean(datasets)
# Printing the mean
print("Mean is :", x)
Output :
Mean is : 4.857142857142857
2. median()
The median() function is used to return the middle value of the numeric data in the list.
Ex
import statistics
datasets = [4, -5, 6, 6, 9, 4, 5, -2]
# Printing median of the
# random data-set
print("Median of data-set is :",statistics.median(datasets))
Output
Median of data-set is : 4.5
3. mode() function
The mode() function returns the most common data that occurs in the list.

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.

3. What's inside datetime?


We can use dir() function to get a list containing all attributes of a module datetime.
import datetime
print(dir(datetime))
Output:
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'date', 'datetime', 'datetime_CAPI', 'sys', 'time',
'timedelta', 'timezone', 'tzinfo']
Commonly used classes in the datetime module are:
1. date Class
2. time Class
3. datetime Class
4. timedelta Class
1. datetime.date Class
 We can instantiate date objects from the date class.
 A date object represents a date (year, month and day).
Date object to represent a date
import datetime
d = datetime.date(2019, 4, 13)
print(d)

date() in the above example is a constructor of the date class.


 The constructor takes three arguments: year, month and day.
We can only import date class from the datetime module. Here's how:
from datetime import date
a = date(2019, 4, 13)
print(a)

The variable a is a date object.

Get current date:


We can create a date object containing the current date by using a class method
named today()
from datetime import date
today = date.today()
print("Current date =", today)
Print today's year, month and day
We can get year, month, day, day of the week etc. from the date object easily.
from datetime import date
# date object of today's date
today = date.today()
print("Current year:", today.year)
print("Current month:", today.month)
print("Current day:", today.day)

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:

# time(hour, minute and second) a = 00:00:00

c = time(hour = 11, minute = 34, second = 56) b = 11:34:56

print("c =", c) c = 11:34:56

# time(hour, minute, second, microsecond) d = 11:34:56.234566

d = time(11, 34, 56, 234566)


print("d =", d)
Print hour, minute, second and microsecond:
Once you create a time object, you can easily print its attributes such as hour, minute etc.
from datetime import time
a = time(11, 34, 56)
print("hour =", a.hour)
print("minute =", a.minute)
print("second =", a.second)
print("microsecond =", a.microsecond)
Output:
hour = 11
minute = 34
second = 56
microsecond = 0
Notice that we haven't passed microsecond argument. Hence, its default value 0 is printed.
3. datetime.datetime:
The datetime module has a class named datetimeclass that can contain information from both
date and time objects.
Python datetime object:
from datetime import datetime
Output:
#datetime(year, month, day)
2018-11-28 00:00:00
a = datetime(2018, 11, 28)
2017-11-28 23:55:59.342380
print(a)
# datetime(year, month, day, hour, minute, second, microsecond)
b = datetime(2017, 11, 28, 23, 55, 59, 342380)
print(b)

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'>

t3 of <class 'datetime.timedelta'> type.


Difference between two timedelta objects:
from datetime import timedelta
t1 = timedelta(weeks = 2, days = 5, hours = 1, seconds = 33)
t2 = timedelta(days = 4, hours = 11, minutes = 4, seconds = 54)
t3 = t1 - t2
print("t3 =", t3)
Output:
t3 = 14 days, 13:55:39
Python format datetime
The way date and time is represented may be different in different places, organizations
etc.
 It's more common to use mm/dd/yyyy in the US, whereas dd/mm/yyyy is more common
in the UK.
Python has ---
1.strftime() and
2. strptime() methods----- to handle this.

1. Python strftime() - datetime object to string


The strftime() method is defined under classes date, datetime and time.
The method creates a formatted string from a given date, datetime or time object.
Format date using strftime()
from datetime import datetime
# current date and time
n = datetime.now()
t = n.strftime("%H:%M:%S")
print("time:", t)
s1 = n.strftime("%m/%d/%Y, %H:%M:%S")
# mm/dd/YY H:M:S format
print("s1:", s1)
s2 = n.strftime("%d/%m/%Y, %H:%M:%S")
# dd/mm/YY H:M:S format
print("s2:", s2)

Output: Here, %Y, %m, %d, %H etc. are format codes.


time: 20:02:51 here, t, s1 and s2 are strings.
s1: 06/15/2020, 20:02:51
s2: 15/06/2020, 20:02:51
The strftime() method takes one or more format codes and returns a formatted string based on
it.
%Y - year [0001,..., 2018, 2019,..., 9999]
%m - month [01, 02, ..., 11, 12]
%d - day [01, 02, ..., 30, 31]
%H - hour [00, 01, ..., 22, 23]
%M - minute [00, 01, ..., 58, 59]
%S - second [00, 01, ..., 58, 59]
2. Python strptime() - string to datetime
The strptime() method creates a datetime object from a given string (representing date and time).

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)

The strptime() method takes two arguments:


1. a string representing date and time
2. format code equivalent to the first argument

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.

It is also called RegEx or re.


For example,

^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")

Output: not matched


import re
match=re.match('^a',’ab')
if match:
print("matched")
else:
print("not matched“)
Output: matched
import re
match=re.match('......a$','formula')
if match:
print("matched")
else:
print("not matched")
Ex:
import re
match=re.match('ma*n','man')
if match:
print("matched")
else:
print("not matched")
Output: matched
Ex:
import re
match=re.match('ma*n','main')
if match:
print("matched")
else:
print("not matched")
Output: not matched
Ex:
import re
match=re.match('ma+n','mn')
if match:
print("matched")
else:
print("not matched")
Output: not matched
Ex:
import re
match=re.match('ma+n','man')
if match:
print("matched")
else:
print("not matched“)
Output: matched
Ex:
import re
match=re.match('ma?n','mn')
if match:
print("matched")
else:
print("not matched")
Output: matched
Ex:
import re
match=re.match('ma?n','maaan')
if match:
print("matched")
else:
print("not matched")
Output: not matched
Ex:
import re
match=re.match('a{2,3}','abc dat')
if match:
print("matched")
else:
print("not matched“)
Output: not matched
import re
match=re.match('a{2,3}','aabc daaat')
if match:
print("matched")
else:
print("not matched“)
Output: matched
Ex:
import re
match=re.match('a|b','ade')
if match:
print("matched")
else:
print("not matched“)
Output: matched
Ex:
import re
match=re.match('a|b',‘cde')
if match:
print("matched")
else:
print("not matched")
Output: not matched
Ex:
import re
match=re.match('(a|b)xz','axz cabxz')
if match:
print("matched")
else:
print("not matched")
Output: matched
import re
match=re.match('(a|b)xz','ab xz')
if match:
print("matched")
else:
print("not matched")
Output: not matched
\ - Backslash
Backlash \ is used to escape various characters including all metacharacters.
For example,
\$a match if a string contains $ followed by a. Here, $ is not interpreted by a
RegEx engine in a special way.
If you are unsure if a character has special meaning or not, you can put \ in front of
it. This makes sure the character is not treated in a special way.
15. Object-Oriented Programming
Object-Oriented Programming(OOP), is all about creating “objects”. An object is a group of
interrelated variables and functions. These variables are often referred to as properties of the
object and functions are referred to as the behavior of the objects. These objects provide a better
and clear structure for the program.

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.

Almost everything in Python is an object, with its properties and methods.

Object is simply a collection of data (variables) and methods (functions) that act on those

data. and, class is a blueprint for the object.


Ex:

We can think of class as a sketch (prototype) of a house. It contains all the details about

the floors, doors, windows etc.

Based on these descriptions we build the house.

House is the object.

we can create many objects from a class. An object is also called an instance of a class

and the process of creating this object is called instantiation.


Creating an Objects or object instantiation in Python:

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.

Instantiation is nothing but creating a new object/instance of a class.

Syntax

object = class_name() # creation of an object is similar to a function call.

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:

Ex: Use the words mysillyobject and abc instead of self:


class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc()
pass Statement in class
class definitions cannot be empty, but if you for some reason have a class definition
with no content, put in the pass statement to avoid getting an error.
Ex:
class Person:
pass
4. Inheritance
Inheritance allows us to define a class that inherits all the methods and properties from
another class.
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called derived class.

Create a Parent Class


Any class can be a parent class, so the syntax is the same as creating any other class:
Ex:
Create a class named Person, with firstname and lastname properties, and a printname method:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname) #Use the Person class to create an object, and
x = Person("John", "Doe") then execute the printname method:
x.printname()
Create a Child Class
To create a class that inherits the functionality from another class, send the parent class
as a parameter when creating the child class:
Example:
Create a class named Student, which will inherit the properties and methods from the Person
class:
class Student(Person):
pass
Note: Use the pass keyword when you do not want to add any other properties or methods
to the class.
Now the Student class has the same properties and methods as the Person class.
Example:
Use the Student class to create an object, and then execute the printname method:
x = Student("Mike", "Olsen")
x.printname()
Example:
class Person: # parent class
def __init__(self, fname, lname):
self.firstname = fname
attributes
self.lastname = lname
def printname(self):
methods
print(self.firstname, self.lastname)
x = Person("John", "Doe")
x.printname()
class Student(Person): # child class
pass
x = Student("Mike", "Olsen")
x.printname()

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.

Example: Add the __init__() function to the Student class:


class Student(Person):
def __init__(self, fname, lname,ag):
#add properties etc.

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.

Similarly, issubclass() is used to check for class inheritance.

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

Here, MultiDerived is derived from classes Base1 and Base2.


Multilevel Inheritance in Python
On the other hand, we can also inherit from a derived class. This is called multilevel
inheritance. It can be of any depth in Python.
In multilevel inheritance, features of the base class and the derived class is inherited into
the new derived class.
Ex:
class Base:
pass
class Derived1(Base):
pass
class Derived2(Derived1):
pass
Here, Derived1 is derived from Base, and Derived2 is derived from Derived1
Data hiding in python:
One of the fundamental concepts which provide data hiding in OOP are:
1. Data Abstraction
2. Data Encapsulation

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.

 This is an abstraction, you know only essential things to operate on switchboard


Abstract Classes
A class containing one or more abstract methods is called an abstract class.
Abstract methods do not contain any implementation. Instead, all the implementations can
be defined in the methods of sub-classes that inherit the abstract class.
An abstract class can have both a normal method and an abstract method.
An abstract class cannot be instantiated, ie., we cannot create objects for the abstract class

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

Here, calculate_area is the abstract method of the abstract class 'Shape'.


The implementation of this abstract class can be defined in the sub-classes that inherit the class
'Shape'.
In the example, 'Rectangle' and 'Circle' are the two sub-classes that inherit the abstract class
'Shape'.
If the implementation of the abstract method is not defined in the derived classes, then the
Python interpreter throws an error.
2. Data encapsulation:
Encapsulation is the process of wrapping up variables and methods into a single entity.
In programming, a class is an example that wraps all the variables and methods defined
inside it.
In the real world, consider your college as an example. Each and every department's
student records are restricted only within the respective department. CSE department faculty
cannot access the ECE department student record and so on. Here, the department acts as
the class and student records act like variables and methods.

Abstraction and Encapsulation are complementary concepts, where –

abstraction focuses upon the observable behaviour of an object and

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'.

class Shape: #protected variables


_length = 10
_breadth = 20
class Circle(Shape):
def __init__(self): #printing protected variables in the derived class
print(self._length)
print(self._breadth)
cr = Circle()
#printing protected variables outsidethe class 'Shape' in which they are defined
print(cr.length)
print(cr.breadth)
output
10
20
AttributeError: 'Circle' object has no attribute 'length'

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.

Similarly in the OOPs concept, polymorphism refers to the ability of a method to


process objects differently depending on their data type or class.

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.

Constructors are generally used for instantiating an object.

The task of constructors is to initialize(assign values) to the data members(variables and


methods) of the class when an object of class is created.

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

You might also like